背景:
开发一个自动化编译的小工具,编译完成后需要将编译成功后的文件上传到平台,但是每次编译成功后的文件都在同一文件夹中,每次在上传的时候需要将文件夹按照日期来排序,本着能偷一点懒就偷一点懒的原则,欲实现在每次编译完成后将本次编译出来的文件放在一个固定的文件夹中,每次上传的时候只需要打开该文件夹,将该文件夹中的全部文件上传即可。
废话说完了,上代码:
# srcfile 需要复制、移动的文件
# dstpath 目的地址
import os
#复制一个文件夹中的所有文件到另一个文件夹
def copy_dir(src_path, target_path):
if os.path.isdir(src_path) and os.path.isdir(target_path):
filelist_src = os.listdir(src_path)
for file in filelist_src:
path = os.path.join(os.path.abspath(src_path), file)
if os.path.isdir(path):
path1 = os.path.join(os.path.abspath(target_path), file)
if not os.path.exists(path1):
os.mkdir(path1)
copy_dir(path, path1)
else:
with open(path, 'rb') as read_stream:
contents = read_stream.read()
path1 = os.path.join(target_path, file)
with open(path1, 'wb') as write_stream:
write_stream.write(contents)
print("成功")
return True
else:
print("失败")
return False
copy_dir(r'.\src',r'.\copy')
运行之后:
可以看到src文件夹中的文件已经全部复制到了copy文件夹中。