1.函数变量
分别为:old_path, fold_feature或者file_feature, target_path
- old_path:需要进行移动的文件/文件夹的所在的路径,比如路径为A/B/C/D,我们要移动D,那么路径为A/B/C
- fold_feature或者file_feature:文件夹或文件所具有的特征。可以是正则、特定字符串、文件后缀
- target_path:需要移动的路径
2.函数功能
使用递归的方式,把该目录下【所有】(包含子目录、子目录的子目录)符合该特征的文件、文件夹移动到指定路径
【不可逆!!!不可以使用Ctrl+Z撤销,慎重!!!】
import os,re
def change_foldpath(old_path, fold_feature, target_path):
try:
for dirpaths, dirnames, filenames in os.walk(old_path):
print(dirpaths,"\n",dirnames,"\n",filenames)
if dirnames:
for anysubdir in dirnames:
if re.search(fold_feature, anysubdir, ):
old_subdir_path = old_path + "/" + anysubdir
new_subdir_path = target_path + "/" + anysubdir
try:
os.rename(old_subdir_path, new_subdir_path)
print("【Folderpath】修改folder_path名成功!")
change_foldpath(new_subdir_path, fold_feature, target_path)
except Exception as reason:
print("【Folderpath】修改folder_path出错!")
print("【Folderpath】出错路径为:{0}\n出错的folder为:{1}".format(dirpaths,anysubdir))
print("【Folderpath】出错原因为:",reason)
else:
print("【Folderpath】该文件夹不匹配目标特征!")
print("【Folderpath】路径为:{0}\nfolder为:{1}".format(dirpaths,anysubdir))
new_subdir_path = old_path + "/" + anysubdir
change_foldpath(new_subdir_path, fold_feature, target_path)
else:
print("【Folderpath】路径{0}中没有文件夹了!".format(dirpaths))
except Exception as reason:
print("【Folderpath】出错路径为:",(dirpaths))
print("【Folderpath】出错原因为:",reason)
def change_filepath(old_path, file_feature, target_path):
try:
for dirpaths, dirnames, filenames in os.walk(old_path):
# print(dirpaths,"\n",dirnames,"\n",filenames)
if filenames:
for anyfile in filenames:
if anyfile == r'.DS_Store':
pass
else:
if re.search(file_feature, anyfile, ):
old_file_path = old_path + "/" + anyfile
new_file_path = target_path + "/" + anyfile
try:
os.rename(old_file_path, new_file_path)
print("【Filepath】更改filename成功!")
except Exception as reason:
print("【Filepath】更改filename出错!")
print("【Filepath】出错路径为:{0}\n出错的file为:{1}".format(dirpaths,anyfile))
print("【Filepath】出错原因为:", reason)
else:
print("【Filepath】该文件加不匹配目标特征!")
print("【Filepath】路径为:{0}\nfile为:{1}".format(dirpaths, anyfile))
else:
print("【Filepath】路径{0}中没有file了!".format(dirpaths))
if dirnames:
for anysubdir in dirnames:
subdir_path = old_path + "/" + anysubdir
change_filepath(subdir_path, file_feature, target_path)
else:
print("【Filepath】路径{0}没有subfolder!".format(dirpaths))
except Exception as reason:
print("【Filepath】出错路径为:",(dirpaths))
print("【Filepath】出错原因为:",reason)
old_path = r"/Users/XXX/Desktop/XXX"
file_feature = "jpg"
fold_feature = "哈哈"
target_path = "/Users/XXXX/Desktop/XXX"
change_filepath(old_path, file_feature, target_path)
# change_foldpath(old_path, fold_feature, target_path)