見出し画像

Python、「ファイル名のリネーム」を試してみた。(フォルダ名_ファイル名)

仕事で、使いたいのでコードを考えてみます。


格納されているフォルダ名を頭に付けたファイル名にしたい。
それによって、違うフォルダに重複するファイル名があったとしても、異なるファイル名に変更することができる。


1、2のフォルダに「あ.txt」というファイル名が存在していたら後工程で困るため。

指定したフォルダ内のデータのみリネームできました。
import os

def rename_files(root_path):
    for file_name in os.listdir(root_path):
        file_path = os.path.join(root_path, file_name)
        if os.path.isfile(file_path):
            parent_folder = os.path.basename(os.path.dirname(file_path))
            new_file_name = f'{parent_folder}_{os.path.basename(file_path)}'
            new_file_path = os.path.join(os.path.dirname(file_path), new_file_name)
            os.rename(file_path, new_file_path)
            print(f'{file_path}{new_file_name} に変更しました')

# ルートディレクトリのパスを指定する
root_directory = 'パスデータを入れてください'
# ルートディレクトリ内のファイル名を変更する
rename_files(root_directory)



全階層のファイルのリネームが出来ました。
import os

def rename_files(root_path):
    # ルートディレクトリ内のすべてのファイルを処理する
    for file_name in os.listdir(root_path):
        file_path = os.path.join(root_path, file_name)
        # ファイルである場合
        if os.path.isfile(file_path):
            # 親フォルダ名を取得する
            parent_folder = os.path.basename(os.path.dirname(file_path))
            # 新しいファイル名を作成する
            new_file_name = f'{parent_folder}_{os.path.basename(file_path)}'
            new_file_path = os.path.join(os.path.dirname(file_path), new_file_name)
            # ファイル名を変更する
            os.rename(file_path, new_file_path)
            # 変更前と変更後のファイル名を表示する
            print(f'{file_path}{new_file_name} に変更しました')
        # ディレクトリである場合
        elif os.path.isdir(file_path):
            # 再帰的に処理する
            rename_files(file_path)

# ルートディレクトリのパスを指定する
root_directory = 'パスを入力してください'
# ルートディレクトリ内のファイル名を変更する
rename_files(root_directory)

最後までお読みいただきありがとうございます。
♡頂けますと、励みになります。

この記事が気に入ったらサポートをしてみませんか?