Tôi cần một cái gì đó chung chung hơn một chút, tức là di chuyển tất cả các tệp từ tất cả các thư mục [phụ] vào thư mục gốc.
Ví dụ bắt đầu với:
root_folder
|----test1.txt
|----1
|----test2.txt
|----2
|----test3.txt
Và kết thúc với:
root_folder
|----test1.txt
|----test2.txt
|----test3.txt
Một hàm đệ quy nhanh chóng hiện các trick:
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)
Bạn thường sẽ gọi nó với cùng một đối số cho root_path
và cur_path
, ví dụ move_to_root_folder(os.getcwd(),os.getcwd())
nếu bạn muốn thử nó trong môi trường python.
Bạn đã thử những gì? 'shutil.move (src, dst)' tài liệu nói "đệ quy di chuyển một tập tin hoặc thư mục (src) đến một vị trí khác (dst)", do đó, nó sẽ làm việc. – jcollado