🙄

【Python】すべてのサブフォルダからファイルをルートディレクトリに移動

に公開
import os
import shutil

def move_all_files_to_current_dir():
    # スクリプトのあるディレクトリを取得
    base_dir = os.path.abspath(os.path.dirname(__file__))

    for root, dirs, files in os.walk(base_dir):
        # base_dir 自体はファイルを移動しない(移動先なので)
        if root == base_dir:
            continue
        for file in files:
            source_path = os.path.join(root, file)
            dest_path = os.path.join(base_dir, file)

            # ファイル名が重複する場合は名前を変える
            if os.path.exists(dest_path):
                name, ext = os.path.splitext(file)
                counter = 1
                while True:
                    new_name = f"{name}_{counter}{ext}"
                    new_dest_path = os.path.join(base_dir, new_name)
                    if not os.path.exists(new_dest_path):
                        dest_path = new_dest_path
                        break
                    counter += 1
            
            shutil.move(source_path, dest_path)
            print(f"Moved: {source_path} -> {dest_path}")

if __name__ == "__main__":
    move_all_files_to_current_dir()

使い方

  1. 上のスクリプトを適当なファイル名で保存。

  2. 移動したいファイルたちがあるディレクトリにそのファイルを置く。

  3. python script.pyをするなどしてpythonでスクリプトを実行すれば完了!

プリインストールされているモジュールだけで実装したのでpip installの手間なし!
楽チン!

このスクリプトが役に立ったらいいね/フォロー/コメントお願いします!

Discussion