最近在备份手机上的照片的时候,纯手工操纵以为有些贫苦,就想写个剧本自动举办。因为备份的时候有些照片以前备份过了,所以需要有个判重操纵。
主要成果在copyFiles()函数里实现,如下:
def copyFiles(src, dst): srcFiles = os.listdir(src) dstFiles = dict(map(lambda x:[x, ''], os.listdir(dst))) filesCopiedNum = 0 # 对源文件夹中的每个文件若不存在于目标文件夹则复制 for file in srcFiles: src_path = os.path.join(src, file) dst_path = os.path.join(dst, file) # 若源路径为文件夹,若存在于方针文件夹,则递归挪用本函数;不然先建设再递归。 if os.path.isdir(src_path): if not os.path.isdir(dst_path): os.makedirs(dst_path) filesCopiedNum += copyFiles(src_path, dst_path) # 若源路径为文件,不反复则复制,不然无操纵。 elif os.path.isfile(src_path): if not dstFiles.has_key(file): shutil.copyfile(src_path, dst_path) filesCopiedNum += 1 return filesCopiedNum
这里我首先利用os.listdir()函数来遍历源文件夹src和方针文件夹dst,获得两个文件列表,但由于我需要判重操纵,因此需要在dst文件列表中举办查询操纵。由于列表的查询效率不高,而字典是一个哈希表,查询效率较高,因此我将方针文件列表转换成一个只有键没有值的字典:
dstFiles = dict(map(lambda x:[x, ''], os.listdir(dst)))
然后我遍历源文件列表,若该路径是一个文件夹,先判定该文件夹在方针路径中是否存在,若不存在,则先建设一个新路径。然后递归挪用本函数。其实不存在的时候更高效的要领是挪用shutil.copytree()函数,但由于此处需要计较拷贝的文件数量,因此就没有挪用该函数。
若该路径是一个文件,则首先判定该文件在方针文件夹中是否存在。若不存在,则拷贝。
由于写这个剧本主要是为了同步手机相册到PC,因此只简朴地判定一下文件名。若要判定差异名但沟通的文件,则可以继承判定一下md5值,这里就不再赘述。
#!/usr/bin/env python # -*- coding: UTF-8 -*- # 输入两个文件夹a和b路径,将a中的文件拷进b,并计较拷贝的文件数。反复的不作处理惩罚。 # pythontab.com 2013-07-19 import os import shutil def copyFiles(src, dst): srcFiles = os.listdir(src) dstFiles = dict(map(lambda x:[x, ''], os.listdir(dst))) filesCopiedNum = 0 # 对源文件夹中的每个文件若不存在于目标文件夹则复制 for file in srcFiles: src_path = os.path.join(src, file) dst_path = os.path.join(dst, file) # 若源路径为文件夹,若存在于方针文件夹,则递归挪用本函数;不然先建设再递归。 if os.path.isdir(src_path): if not os.path.isdir(dst_path): os.makedirs(dst_path) filesCopiedNum += copyFiles(src_path, dst_path) # 若源路径为文件,不反复则复制,不然无操纵。 elif os.path.isfile(src_path): if not dstFiles.has_key(file): shutil.copyfile(src_path, dst_path) filesCopiedNum += 1 return filesCopiedNum def test(): src_dir = os.path.abspath(raw_input('Please enter the source path: ')) if not os.path.isdir(src_dir): print 'Error: source folder does not exist!' return 0 dst_dir = os.path.abspath(raw_input('Please enter the destination path: ')) if os.path.isdir(dst_dir): num = copyFiles(src_dir, dst_dir) else: print 'Destination folder does not exist, a new one will be created.' os.makedirs(dst_dir) num = copyFiles(src_dir, dst_dir) print 'Copy complete:', num, 'files copied.' if __name__ == '__main__': test()