【问题标题】:merge txt files issue with output file not being txt合并 txt 文件问题,输出文件不是 txt
【发布时间】:2021-08-03 02:21:43
【问题描述】:

下面是我将几个 txt 文件合并在一起的代码。

import os

with open('outfile', 'w') as outfile:
    for filename in os.listdir(os.getcwd()):
        if (filename.endswith(".txt")):
            with open(filename) as infile:
                for line in infile:
                    outfile.write(line)

输出文件 'outfile' 是合并后的文件,但它不是 txt。
然后我尝试了

with open('outfile.txt', 'w') as outfile:

进程卡住了,没有任何内容写入 outfile.txt
有谁知道如何修理它?我的目标是将输出文件保存为 txt。

【问题讨论】:

    标签: python merge output


    【解决方案1】:

    我猜你可能遇到文件锁,当有一个进程以write打开文件时,其他进程在操作该文件时有问题。
    您可以尝试绕过该文件

    import os
    
    with open('outfile.txt', 'w') as outfile:
        for filename in os.listdir(os.getcwd()):
            if (filename.endswith(".txt")) and filename!='outfile.txt':
                with open(filename) as infile:
                    for line in infile:
                        outfile.write(line)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      相关资源
      最近更新 更多