0

我有 3 个文件1.txt, 2.txt,3.txt并且我正在尝试将这些文件的内容连接到 Python 中的一个输出文件中。谁能解释一下为什么下面的代码只写了1.txtand 而不是2.txtor的内容3.txt?我确定这很简单,但我似乎无法找出问题所在。

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

2 回答 2

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)
于 2011-08-27T19:58:27.950 回答
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)
于 2011-08-27T19:58:54.113 回答