本文的形成:首先查找理解网上提供的各种方法,然后在本地进行调试,确定可以使用后进行综合,并发布记录。
本文为转载文章,但由于时间比较急,所以忘记保存转载的地址,之后能找到的话会补上。
方法排序按照我的需求,无优劣之分
1. 文件夹下的所有文件(包括子目录文件)拷贝到目标文件夹下
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| def copy1(source_path, target_path): if not os.path.exists(target_path): os.makedirs(target_path)
if os.path.exists(source_path): for root, dirs, files in os.walk(source_path): for file in files: src_file = os.path.join(root, file) shutil.copy(src_file, target_path) print('end')
print('copy files finished!')
|
2. 文件夹整体拷贝
代码:
1 2 3 4 5 6 7 8 9 10 11 12
| def copy_all_dir(source_path, target_path): if not os.path.exists(target_path): os.makedirs(target_path)
if os.path.exists(source_path): shutil.rmtree(target_path)
shutil.copytree(source_path, target_path) print('copy dir finished!')
|
3. 复制文件夹以及文件夹下的子文件
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| def copyDir(sourcePath, targetPath): if not os.path.isdir(sourcePath): return '源目录不存在' sourceStack = collections.deque() sourceStack.append(sourcePath) targetStack = collections.deque() targetStack.append(targetPath) while True: if len(sourceStack) == 0: break sourcePath = sourceStack.pop() listName = os.listdir(sourcePath)
targetPath = targetStack.pop() if not os.path.isdir(targetPath): os.makedirs(targetPath) for name in listName: sourceAbs = os.path.join(sourcePath, name) targetAbs = os.path.join(targetPath, name) if os.path.isdir(sourceAbs): if not os.path.exists(targetAbs): os.makedirs(targetAbs) sourceStack.append(sourceAbs) targetStack.append(targetAbs) if os.path.isfile(sourceAbs): shutil.copyfile(sourceAbs,targetAbs)
def unzip_files(obj): ss = os.listdir(obj) for file in ss: if file.endswith(".zip"): zip_fileName = obj+file zip_file = zipfile.ZipFile(zip_fileName) zz = file.split(".zip")[0] ff =obj + zz if os.path.isdir(ff): pass else: os.mkdir(ff) for names in zip_file.namelist(): zip_file.extract(names,ff) zip_file.close() time.sleep(2) os.remove(zip_fileName) return zz
def update_dest_folder(object): dd = [] if os.path.isdir(object): updatefoldername = os.listdir(object) for ff in updatefoldername: updatefoldername = object+ "/" +ff if os.path.isdir(updatefoldername): dd.append(updatefoldername) else: pass return dd if __name__ == '__main__': srcPath = "E:/update/" ss = unzip_files(srcPath) tPath = "E:/test" names = update_dest_folder(tPath) sorce_real = srcPath + "/"+str(ss)+"/"+str(ss) print(sorce_real) for destPath in names: copyDir(sorce_real, destPath)
|
4. python复制时不覆盖重命名
代码:
1 2 3 4 5 6 7 8 9 10
| def get_new_name(dir, f):
if os.path.exists(os.path.join(dir, f)): s="%s_%s%s" % (os.path.splitext(f)[0], "copy", os.path.splitext(f)[1]) return get_new_name(dir, s) return os.path.join(dir, f)
p=get_new_name(r"C:\Users\lishihang\Desktop\新建文件夹","1.txt") shutil.copy(r"C:\Users\lishihang\Desktop\1.txt",p)
|