2012-03-12 41 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)