我需要一些更通用的东西,即将所有文件从所有[sub]+文件夹移到根文件夹中。
例如,开始于:root_folder
|----test1.txt
|----1
|----test2.txt
|----2
|----test3.txt
结果是:root_folder
|----test1.txt
|----test2.txt
|----test3.txt
一个快速的递归函数可以做到这一点:import os, shutil, sys
def move_to_root_folder(root_path, cur_path):
for filename in os.listdir(cur_path):
if os.path.isfile(os.path.join(cur_path, filename)):
shutil.move(os.path.join(cur_path, filename), os.path.join(root_path, filename))
elif os.path.isdir(os.path.join(cur_path, filename)):
move_to_root_folder(root_path, os.path.join(cur_path, filename))
else:
sys.exit("Should never reach here.")
# remove empty folders
if cur_path != root_path:
os.rmdir(cur_path)
如果您想在python环境中尝试,通常会用相同的参数来调用它,例如root_path和cur_path,例如move_to_root_folder(os.getcwd(),os.getcwd())。