【问题标题】:Python merge multiple txt filesPython合并多个txt文件
【发布时间】:2012-11-23 09:08:15
【问题描述】:

我尝试使用此代码合并文件夹中的多个 TXT 文件,但它不起作用:

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

有人有想法吗?

【问题讨论】:

  • 它不工作...你能指定细节吗,你的目的地会被覆盖吗
  • 也没有为我覆盖或生成任何内容
  • 看到/tmpC:\users 在同一个代码中我很困惑。你是什​​么系统?另外,请改写r"C:\Users...",以防止转义。
  • 好的。更改了路径,我得到了一个巨大的 TXT 文件,其中所有 TXT 文件的所有内容都被合并,但它应该只合并路径中的 TXT 文件。

标签: python text merge


【解决方案1】:

编辑:您在写入 path 内部时正在创建 fileappend.txt。根据写入刷新到磁盘的时间,您可能正在尝试读取要附加到的文件。这会导致很多奇怪的事情。考虑不要将fileappend.txt 放在path 中,或者在完成后将其移到那里。

你可以把你的代码写得更整洁:

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

【讨论】:

  • 嗨,我试过你的代码,但得到了这个:NameError: global name 'fnmatch' is not defined
  • 你需要import fnmatch
  • 现在我得到了这个:IOError: [Errno 2] No such file or directory: 'fileappend.txt' 但文件存在但没有内容。
【解决方案2】:

你可以使用 cat(shell 命令)

cat 1.txt>>2.txt

在python中,你可以使用os.system()来使用shell命令

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    相关资源
    最近更新 更多