[英]Optimizing simple Python file matching & replacement script
just wondering if anyone has a suggestion for how I can optimize my simple but slow file replacement script: 只是想知道是否有人对我如何优化简单但缓慢的文件替换脚本提出建议:
def switchFiles(args):
for root1, dirs1, files1 in os.walk(args.folder):
for f1 in files1:
for root2, dirs2, files2 in os.walk(args.database):
for f2 in files2:
if fnmatch.fnmatch(f1, f2):
command = 'cp '+os.path.join(root1, f1)+' '+os.path.join(root2, f2)
print(command)
os.system(command)
Thanks! 谢谢!
This is a clean up code: 这是一个清理代码:
def switchFiles(args):
pairs = []
for root1, dirs1, files1 in os.walk(args.folder):
for f1 in files1:
for root2, dirs2, files2 in os.walk(args.database):
for f2 in files2:
if f1 == f2:
pairs.append(os.path.join(root1, f1), os.path.join(root2, f2))
for src, dst in pairs:
shutil.copyfile(src, dst)
if args.folder and args.database are separate (not subdir), and all file's name in their dir are unique, then you can do this: 如果args.folder和args.database是分开的(不是subdir),并且其目录中的所有文件名都是唯一的,则可以执行以下操作:
def switchFiles(args):
f, d = {}, {}
for root1, dirs1, files1 in os.walk(args.folder):
for f1 in files1:
f[f1] = os.path.join(root1, f1)
for root2, dirs2, files2 in os.walk(args.database):
for f2 in files2:
d[f2] = os.path.join(root2, f2)
ns = set(f.keys()) & set(d.keys())
for n in ns:
shutil.copyfile(f[n], d[n])
I think this one will be faster if args.folder has just few files. 我认为,如果args.folder只有几个文件,则此方法会更快。
def switchFiles(args):
srclst = {}
for root, dirs, files in os.walk(args.folder):
rootp = (root,)
for filename in files:
srclst[filename] = rootp
for root, dirs, files in os.walk(args.database):
for filename in files:
srcrootp = srclst.get(filename)
if not srcrootp:
continue
srcpath = os.path.join(srcrootp[0], filename)
dstpath = os.path.join(root, filename)
print "replace", srcpath, dstpath
shutil.copy(srcpath, dstpath)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.