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.")
この記事が気に入ったらサポートをしてみませんか?