2013-07-19 57 views
6

我已經編寫了以下腳本來將目錄中的所有文件連接成一個文件。python腳本將目錄中的所有文件連接成一個文件

可以這樣進行優化,在

  1. 慣用蟒蛇方面

  2. 時間

下面是摘錄:

import time, glob 

outfilename = 'all_' + str((int(time.time()))) + ".txt" 

filenames = glob.glob('*.txt') 

with open(outfilename, 'wb') as outfile: 
    for fname in filenames: 
     with open(fname, 'r') as readfile: 
      infile = readfile.read() 
      for line in infile: 
       outfile.write(line) 
      outfile.write("\n\n") 
+7

針對時間進行了優化?使用「貓* .txt> all.txt」:) –

+0

可能重複[結合多個文本文件到一個文本文件使用python](http://stackoverflow.com/questions/17749058/combine-multiple-text-files- into-one-text-file-using-python) – llb

回答

23

使用shutil.copyfileobj複製數據:

import shutil 

with open(outfilename, 'wb') as outfile: 
    for filename in glob.glob('*.txt'): 
     if filename == outfilename: 
      # don't want to copy the output into the output 
      continue 
     with open(filename, 'rb') as readfile: 
      shutil.copyfileobj(readfile, outfile) 

shutil從以塊的readfile對象讀取,將其寫入到outfile文件對象直。請勿使用readline()或迭代緩衝區,因爲您不需要查找行尾的開銷。

使用相同的模式讀取和寫入;這在使用Python 3時尤爲重要;我在這裏使用二進制模式。

+0

爲什麼使用相同模式進行書寫和閱讀很重要? –

+1

@JuanDavid:因爲shutil將對另一個文件對象使用'.read()'調用,將'.write()'調用傳遞給另一個文件對象,將讀取的數據從一個傳遞到另一個。如果其中一個以二進制模式打開,另一個以文本形式打開,則會通過不兼容的數據(二進制數據傳輸到文本文件或文本數據傳輸到二進制文件)。 –

0

可以遍歷l直接文件對象的分級表,沒有閱讀整個事情到內存:

with open(fname, 'r') as readfile: 
    for line in readfile: 
     outfile.write(line) 
1

不需要使用那麼多的變量。

with open(outfilename, 'w') as outfile: 
    for fname in filenames: 
     with open(fname, 'r') as readfile: 
      outfile.write(readfile.read() + "\n\n") 
1

fileinput模塊提供了一個自然的方式來遍歷多個文件

for line in fileinput.input(glob.glob("*.txt")): 
    outfile.write(line) 
+0

如果不一次只限於閱讀一行,這會更好。 – Marcin

+0

@Marcin,那是對的。我曾經認爲這是一個很酷的解決方案 - 直到我看到Martijn Pieter的'shutil.copyfileobj' humdinger。 – iruvar

1

使用Python 2.7,我做的

outfile.write(infile.read()) 

一些 「標杆」 測試VS

shutil.copyfileobj(readfile, outfile) 

我迭代了超過20個.txt文件,大小從63 MB到313 MB,聯合文件大小約爲2.6 GB。在這兩種方法中,正常讀取模式比二進制讀取模式執行得更好,shutil.copyfileobj通常比outfile.write快。

當比較最差的組合(outfile.write,二進制模式)的最佳組合(shutil.copyfileobj,正常讀取模式),差異相當顯著:

outfile.write, binary mode: 43 seconds, on average. 

shutil.copyfileobj, normal mode: 27 seconds, on average. 

outfile中有一個最終的尺寸在正常讀取模式下爲2620 MB,在二進制讀取模式下爲2578 MB。

+0

有趣。那是什麼平臺? – ellockie

+0

我大致在兩個平臺上工作:Linux Fedora 16,不同的節點或Windows 7 Enterprise SP1,帶有Intel Core(TM)2 Quad CPU Q9550,2.83 GHz。我認爲這是後者。 –

+0

感謝您的信息! – ellockie

相關問題