【问题标题】:Problem with file concatenation in Python?Python中的文件连接问题?
【发布时间】:2011-08-27 19:51:41
【问题描述】:

我有 3 个文件 1.txt2.txt3.txt,我正在尝试将这些文件的内容连接到 Python 中的一个输出文件中。谁能解释一下为什么下面的代码只写1.txt的内容而不是2.txt3.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)

感谢您的帮助!

【问题讨论】:

    标签: python file-io concatenation shutil


    【解决方案1】:

    你不断地覆盖同一个文件。

    任意使用:

    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)
    

    【讨论】:

    • 我不确定它是否覆盖了同一个文件;在这种情况下,你不会得到3.txt 的副本吗?
    • 文件名不一定按词汇顺序存储在目录中。
    • @yi_H:哦,是的,我确实知道。好久没用了谢谢。
    • 啊!谢谢,这就是问题所在。我很欣赏这个解释,因为它希望能帮助我在未来纠正这些过度网站。让我感到困惑的是让汤姆感到困惑的同一件事。
    【解决方案2】:

    我认为您的代码的问题在于,在每次循环迭代中,您实际上都是在向自己添加文件。

    如果你手动展开循环,你会明白我的意思:

    # 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)
    

    【讨论】:

    • -1 concat_file 在原始文件中旨在服务于 output_file 在您的示例中的用途。
    猜你喜欢
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多