2011-08-27 85 views
0

我有3個文件1.txt2.txt3.txt,我想這些文件的內容串接爲Python中的一個輸出文件。任何人都可以解釋爲什麼只以下的代碼寫的1.txt的內容,而不是2.txt3.txt?我確定這件事很簡單,但我似乎無法弄清楚問題所在。Python中的文件連接問題?

import glob 
import shutil 

for my_file in glob.iglob('/Users/me/Desktop/*.txt'): 
    with open('concat_file.txt', "w") as concat_file: 
     shutil.copyfileobj(open(my_file, "r"), concat_file) 

感謝您的幫助!

回答

4

你不斷地覆蓋相同的文件。

要麼使用:

with open('concat_file.txt', "a") 

with open('concat_file.txt', "w") as concat_file: 
    for my_file in glob.iglob('/Users/me/Desktop/*.txt'): 
     shutil.copyfileobj(open(my_file, "r"), concat_file) 
+0

我不知道它的覆蓋相同的文件;那麼你會不會在這種情況下得到一個'3.txt'的副本? –

+0

沒有,'glob'不返回的結果排序 –

+0

文件名不一定存儲在詞彙順序的目錄。 – kindall

0

我相信,有什麼錯你的代碼是在每一個循環迭代,你基本上是將文件添加到自己。

如果手動展開循環,你會明白我的意思:

# my_file = '1.txt' 
concat_file = open(my_file) 
shutil.copyfileobj(open(my_file, 'r'), concat_file) 
# ... 

我建議事先決定你想要的文件中的所有文件複製到,也許是這樣的:

import glob 
import shutil 

output_file = open('output.txt', 'w') 

for my_file in glob.iglob('/Users/me/Desktop/*.txt'): 
    with open('concat_file.txt', "w") as concat_file: 
     shutil.copyfileobj(open(my_file, "r"), output_file) 
+0

-1'原concat_file'旨在充當的是'output_file'做你的樣品中的目的。 –