因某些业务需求,需要移动大量文件到根目录。
这里分循环和递归两种实现方式
1. 覆盖掉同名文件的实现方式
all_dirs = []
all_files = []
path = os.getcwd()
list_files = os.walk(path)
for dirpath,dirnames,filenames in list_files:
for dir in dirnames:
all_dirs.append(os.path.join(dirpath,dir))
for file in filenames:
all_files.append(os.path.join(dirpath,file))
abs_file = os.path.join(dirpath,file)
try:
shutil.move(abs_file,path+"\\"+file)
print("move : " + file)
pass
except Exception as e:
print(e)
# 删除文件夹
# for dir in all_dirs:
# try: shutil.rmtree(dir)
# except Exception as e:
# print(e)
print("done")
2.递归实现并保留重复文件
# coding=utf-8
import shutil
import os
def move(src,dst):
ls = os.listdir(os.path.pardir)
dst_2 = dst.split('\\')
if dst_2[-1] in ls and os.path.getsize(dst) != os.path.getsize(src):
dst = dst[0:-4] + '-' + dst[-4:-1] + dst[-1]
move(src,dst)
return
print("MOVE : "+src+" TO "+dst,file=history)
shutil.move(src,dst)
def move_file(file_list,depth):
for file in file_list:
if os.path.isdir(file):
os.chdir(file)
ls = os.listdir()
move_file(ls,depth+1)
os.chdir(os.path.pardir)
else:
# for i in range(depth):
# print(" - ",end="")
# print(file)
move(os.path.join(os.getcwd(),file),os.path.join(parent_dir,file))
pass
history = open('history.txt','a+')
cwd = os.listdir()
parent_dir = os.getcwd()
cwd_2 = []
for folder in cwd:
if os.path.isdir(folder):
cwd_2.append(folder)
move_file(cwd_2,0)