2015-06-30 28 views
1

追加我的位置/根N檔如下文件在python

result1.txt 
abc 
def 

result2.txt 
abc 
def 
result3.txt 
abc 
def 

等。 我必須創建一個名爲result.txt的合併文件,並將所有結果文件中的所有值連接到位置/ root/samplepath中的n個文件。

+0

[Python的連接文本文件(http://stackoverflow.com/questions/13613336/python-concatenate-text-files) – albert

+2

'貓可能重複result?.txt> result.txt'? –

+0

到目前爲止您已經嘗試過Waht嗎?爲什麼不使用貓? – frlan

回答

3

可能更容易使用貓,正如其他人所建議的那樣。如果你必須用Python來完成,這應該起作用。它查找目錄中的所有文本文件並將其內容附加到結果文件中。

import glob, os 

os.chdir('/root') 

with open('result.txt', 'w+') as result_file: 
    for filename in glob.glob('result*.txt'): 
     with open(filename) as file: 
      result_file.write(file.read()) 
      # append a line break if you want to separate them 
      result_file.write("\n") 
+0

如果我在目錄中有其他txt文件,該怎麼辦。如果我使用這個glob,那麼所有的txt文件將被連接起來? – Punkster

+1

如果你只希望在其中有'result'關鍵字的文件,那麼執行'glob.glob('result * .txt')'。 – Brobin

+0

非常感謝@Brobin – Punkster

-1

這可能是這樣

讓一個簡單的方法舉例說,我的文件script.py是一個文件夾中,並連同該腳本有一個名爲測試文件夾,裏面所有的命名爲喜歡file_0,file_1文本文件....

import os 

#reads all the files and put everything in data 
number_of_files = 0 
data =[] 
for i in range (number_of_files): 
    fn = os.path.join(os.path.dirname(__file__), 'testing/file_%d.txt' % i) 
    f = open(fn, 'r') 
    for line in f: 
      data.append(line) 
    f.close() 


#write everything to result.txt 
fn = os.path.join(os.path.dirname(__file__), 'result.txt') 
f = open(fn, 'w') 
for element in data: 
    f.write(element) 
f.close()