![見出し画像](https://assets.st-note.com/production/uploads/images/130852690/rectangle_large_type_2_78ec5107594a34f75fdd00202cf5bafa.png?width=1200)
Python、「階層をまたぐデータ移動」再び試してみた。
import os
import shutil
def move_files_to_top_folder(source_folder):
# Recursively move files from all subfolders to the top level
for root, dirs, files in os.walk(source_folder):
for file in files:
file_path = os.path.join(root, file)
# Move file to the top level
shutil.move(file_path, os.path.join(source_folder, file))
# Remove empty subfolders
for root, dirs, files in os.walk(source_folder, topdown=False):
for dir in dirs:
dir_path = os.path.join(root, dir)
try:
os.rmdir(dir_path)
except OSError:
pass
if __name__ == "__main__":
target_folder = "親フォルダのパスを入力してください"
print(f"Current working directory: {os.getcwd()}")
# Call the function to move all files to the top level
move_files_to_top_folder(target_folder)
print(f"Moved all files to the top level of the folder.")
![](https://assets.st-note.com/img/1707903571259-pwQtS6ycEF.png)
![](https://assets.st-note.com/img/1707903668020-AZ7PSBUX5y.png)
フォルダは、削除してくれなくてよかったのですがこれしか分かりませんでした。
まぁ、いっか。
![](https://assets.st-note.com/img/1707903720985-pO846qYWsI.png?width=1200)