介绍
小编给大家分享一下linux下python多线程如何实现递归复制文件夹及文件夹中的文件,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!
本文是利用python复制文件夹刚开始写了一个普通的递归复制文件夹,,然后想了想觉得对io频繁的程序螺纹线程还比较友好,就写了个多线程版本的,最恶心人的地方就是路径,其他都还好吧,
import 操作系统 import 线程 import 多处理 length_of_folder =0 def 拷贝文件(路径): if os.path.isdir(路径): 打印才能(“- - - - - - - - - - - - % s", %, (“Testfortherading_", +, & # 39;/& # 39;, +,路径(length_of_folder:))) os.makedirs才能(“Testforthreading_", +, & # 39;/& # 39;, +,路径[length_of_folder:]) 时间=filenames os.listdir(路径) for filename 拷贝文件名: if 才能;os.path.isdir(时间+ Path & # 39;/& # 39;, +,文件名): ,,,# ps =,“Testforthreading_", +“/? +,路径(length_of_folder:) ,,,#打印(“% s", %,(时间+ ps & # 39;/& # 39;, +,文件名)) ,,,# os.mkdir(时间+ ps & # 39;/& # 39;, +,文件名) ,,,temp =, Path +, & # 39;/& # 39; +,文件名 ,,,t =, threading.Thread(目标=copyfile ,, args=(临时)) ,,,t.start () 其他的才能: ,,,f =,开放(时间+ Path & # 39;/& # 39;, +, filename ,, & # 39; rb # 39;) ,,,content =, f.read () ,,,F =,开放(& # 39;Testforthreading_& # 39;, +, & # 39;/& # 39;, +,路径[length_of_folder:] +, & # 39;/& # 39;, +, filename ,, & # 39; wb # 39;) ,,,F.write(内容) ,,,f.close () ,,,F.close () def main (): ““““““ 时间=foldername 输入(“Please  input 从而folder 你want 用复制:“) length_of_folder =, len (foldername) if os.path.isdir (“Testforthreading_"): os.removedirs才能(“Testforthreading_") os.mkdir (“Testforthreading_") 拷贝文件(foldername) # p =, multiprocessing.Pool (10) .Queue # que =, multiprocessing.Manager () () if __name__ ==,“__main__": main ()
<>强ps: Python多进程递归复制文件夹中的文件强>
import 多处理 import 操作系统 import reimport 时间 #,源文件夹地址,目标文件夹地址 SOUR_PATH =,““ DEST_PATH =,““ #,源文件列表,文件夹列表 SOUR_FILE_LIST =,列表() SOUR_DIR_LIST =,列表() def 导线(source_path): “““才能递归遍历源文件夹,获取文件夹列表,文件列表 :才能param source_path:,用户指定的源路径 “才能”;“ if 才能os.path.isdir (source_path): ,,,SOUR_DIR_LIST.append (source_path) ,,,for temp 拷贝os.listdir (source_path): ,,,,,new_source_path =, os.path.join (source_path,临时) ,,,,,遍历(new_source_path) 其他的才能: ,,,SOUR_FILE_LIST.append (source_path) def copy_file (sour_file,队列,还以为;dest_file): “““才能复制文件列表中的文件到指定文件夹 :才能param 队列:,队列,用于监测进度 :才能param sour_file: :才能param dest_file: “才能”;“ #才能,time . sleep (0.1) 尝试才能: ,,,old_f =,开放(sour_file,“rb") ,,,new_f =,开放(dest_file,“wb") except 才能;Exception  as 随著: ,,,print (ret) 其他的才能: ,,,content =, old_f.read () ,,,new_f.write(内容) ,,,old_f.close () ,,,new_f.close () queue.put才能(sour_file) def main (): source_path =,才能输入(“请输入需要复制的文件夹的路径:\ n") SOUR_PATH 才能=source_path DEST_PATH 才能=,SOUR_PATH +,“[副本), #,才能dest_path =,输入(“请输入目标文件夹路径“) #,才能DEST_PATH =dest_path 打印才能(“祝辞祝辞祝辞源文件夹路径:“,,SOUR_PATH) 打印才能(“祝辞目标文件夹路径:“,,DEST_PATH) 打印才能(“开始计算文件…“) 时间=queue 才能;multiprocessing.Manager () .Queue () 时间=po 才能;multiprocessing.Pool (5) 遍历(source_path)才能 打印才能(“创建目标文件夹…“) for 才能;sour_dir  SOUR_DIR_LIST:拷贝 ,,,dest_dir =, sour_dir.replace (SOUR_PATH, DEST_PATH) ,,,试一试: ,,,,,os.mkdir (dest_dir) null null null null null null null null null null null null null null null null null null null null null null null null nulllinux下python多线程如何实现递归复制文件夹及文件夹中的文件