Python合并多个txt文件 [英] Python merge multiple txt files

查看:83
本文介绍了Python合并多个txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用此代码合并一个文件夹中的多个TXT文件,但无法正常工作:

I tried to merge multiple TXT-files in a folder with this code but it is not working:

import os,shutil
path = "C:/Users/user/Documents/MergeFolder"
f=open(path + "/fileappend.txt","a")
for r,d,fi in os.walk(path):
     for files in fi:
         if files.endswith(".txt"):                         
              g=open(os.path.join(r,files))
              shutil.copyfileobj(g,f)
              g.close()
f.close()

有人有主意吗?

推荐答案

您正在path内创建fileappend.txt,同时对其进行写入.根据将写入内容刷新到磁盘的时间,您可能正在尝试读取要附加到的文件.嗯,这会引起很多怪异.考虑不要将fileappend.txt放在path内,或者在完成后仅将其移到那里.

you're creating fileappend.txt inside path, while writing to it. Depending on when the writes are flushed to disk, you may be trying to read the file that you're appending to. This would cause, well, lots of weirdness. Consider not placing fileappend.txt inside path, or else just moving it there when you're done.

您可以更简洁地编写代码,如下所示:

You can write your code more neatly as:

with open(os.path.join(path, "fileappend.tmp"), "a") as dest:
    for _, _, filenames in os.walk(path):
        for filename in fnmatch.filter(filenames, "*.txt"):
            with open(filename) as src:
                shutil.copyfileobj(src, dest)
os.rename(os.path.join(path, "fileappend.tmp"), "fileappend.txt")

这篇关于Python合并多个txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆