2012-03-12 85 views
0

只是想知道如果任何人有我如何才能优化我的简单而缓慢的文件替换脚本一个建议:优化简单的Python文件匹配和替换脚本

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) 

谢谢!

+2

Cache'files2'并使用'shutil.copy()'而不是运行'cp'。 – Blender 2012-03-12 17:29:42

+0

为什么使用'fnmatch.fnmatch'来比较两个简单的字符串?我错过了什么吗? – 2012-03-12 17:30:30

+0

感谢搅拌机。大卫,我认为这种情况只是早期尝试的碎片。将改为==,并感谢您指出。 – barnhillec 2012-03-12 17:33:27

回答

1

这是一个清理代码:

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) 

如果args.folder和args.database是分开的(不是子目录),和所有的文件在其目录名称是独一无二的,那么你可以这样做:

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]) 
0

我觉得如果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)