测试1(直接把B文件夹移动到了A里,成为了A的子文件夹)
import os
import shutil# 移动文件夹,B文件夹在当前目录没有了,跑到了A的子文件里
##
shutil.move('./example1/B/', './example1/A/')
测试2(B文件不动,将B文件里的所有的子文件夹移动到A内)
import os
import shutildef move_folder(source_folder, destination_folder,overlapp=False):# 创建目标文件夹os.makedirs(destination_folder, exist_ok=True)destFileFolder = os.listdir(destination_folder)# 遍历源文件夹中的所有文件和文件夹for subFileFolder in os.listdir(source_folder):print(subFileFolder)source_item = os.path.join(source_folder, subFileFolder)if(subFileFolder in destFileFolder):if(not overlapp):print("原始文件夹{}不移动!!!".format(source_item))else:# 把原始的文件给删除,然后再移动print("未实现,应该首先把这个结果给删除点,然后复制过来。。。。")else:shutil.move(source_item, destination_folder)print("{}-->移动-->{}完成!!!".format(source_item,destination_folder))
# 示例用法# delete_list
file_path ='./example2/A/'
file_list = os.listdir(file_path)
# 从文件夹中删掉
if(".DS_Store" in file_list):print("There is .DS_Store in filefolder, delete it!!!")file_list.remove(".DS_Store")os.remove(file_path+"/.DS_Store")
else:print("No .DS_Store in file folder")move_folder("./example2/B/","./example2/A/")
结果如下
移动子文件夹
import pickle
import os
import shutil
read_path="/Users/yxk/Desktop/核磁项目/527检查修改mask/ThreeD_patient_list.pkl"
base_sample_path = "/Volumes/My Passport/yxk_move_sample/file/"
with open(read_path,"rb") as f: # Python 3: open(..., 'rb')ThreeD_patient_list=pickle.load(f)print(ThreeD_patient_list)for patient in ThreeD_patient_list:shutil.move(base_sample_path+patient,"/Volumes/My Passport/yxk_move_sample/ThreeDT1样本/")