1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 复制文件夹下所有文件(包括子文件夹) 到一个文件夹

复制文件夹下所有文件(包括子文件夹) 到一个文件夹

时间:2021-06-28 09:46:31

相关推荐

复制文件夹下所有文件(包括子文件夹) 到一个文件夹

把子目录文件复制到当前目录

读取文件夹下所有文件路经,包括子文件夹下

import PIL.Image as Imageimport os import shutildef list_folder(root,use_absPath=True, func=None):""":param root: 文件夹根目录:param func: 定义一个函数,过滤文件:param use_absPath: 是否返回绝对路径, false :返回相对于root的路径:return:"""root = os.path.abspath(root)if os.path.exists(root):print("遍历文件夹【{}】......".format(root))else:raise Exception("{} is not existing!".format(root))files = []# 遍历根目录,for cul_dir, _, fnames in sorted(os.walk(root)):for fname in sorted(fnames):path = os.path.join(cul_dir, fname)#.replace('\\', '/')if func is not None and not func(path):continueif use_absPath:files.append(path)else:files.append(os.path.relpath(path,root))print(" find {} file under {}".format(len(files), root))return files

整理文件夹下所有文件(包括子文件夹),到一个文件夹下

def copy_files(src_dir,dst_dir):""":param src_dir: 原文件夹:param dst_dir: 目标文件夹:Func: 复制文件夹下所有文件(包括子目录下)到另外一个文件夹下,原文件夹的子目录也会copy到dst_dir的根目录下。Note: src_dir/dir1/dir2/fname -> dst_dir/dir1_dir2_fname:return:"""file_paths=list_folder(src_dir)if len(file_paths)==0:returnfnames= [ os.path.relpath(file_path,src_dir).replace("\\","_") for file_path in file_paths ] if not os.path.exists(dst_dir):print("Log: make dir :{}".format(dst_dir))os.makedirs(dst_dir)num_copy=0for src_path,fname in zip(file_paths,fnames):dst_path=os.path.join(dst_dir,fname)if os.path.exists(dst_path):continueelse:num_copy+=1shutil.copy(src_path,dst_path)#time.sleep(1)#command_str=" ".join(["copy",src_path,os.path.join(dst_dir,fname)]) #os.popen(command_str)print("Log: copy {} files".format(num_copy))

测试

src_dir="F:\old\数据集\KolektorSDD"dst_dir="F:\old\数据集\KolektorSDD_merge"copy_files(src_dir,dst_dir)#遍历文件夹【F:\old\数据集\KolektorSDD】......#find 798 file under F:\old\数据集\KolektorSDD#Log: make dir :F:\old\数据集\KolektorSDD_merge#Log: copy 798 files

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。