简体   繁体   English

垂直合并 .txt 文件的内容

[英]Merge vertically the content of .txt files

I would like to merge the content of specific .txt files VERTICALLY in a folder (directory) via one commant in python,我想通过python中的一个命令将特定.txt文件的内容垂直合并到一个文件夹(目录)中,

I have tried the following code but its no use (I mean it works, but the put the output is shown as one horizontal plot, and not multiple vertical lines)我已经尝试了以下代码,但没有用(我的意思是它有效,但输出显示为一个水平图,而不是多条垂直线)

import glob

read_files = glob.glob("mypath/finalR*.txt")

with open("result5.txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(infile.read())

could you help me?你可以帮帮我吗?

Couple of things to note:需要注意的几点:

  1. b is for opening a file in binary mode. b用于以二进制模式打开文件。 You don't need this since you are working with text files.您不需要这个,因为您正在处理文本文件。
  2. Since you have only a couple of files, I suggest you read all the lines into a Python list and write into the output file once.由于您只有几个文件,我建议您将所有行读入 Python 列表并写入输出文件一次。

Keeping these in mind, the solution now looks like the following: 记住这些,现在的解决方案如下所示:
 read_files = glob.glob("mypath/finalR*.txt") lines = [] for file in read_files: with open(file, "r") as f: lines.extend(x.strip() for x in f.readlines()) with open("result.txt", "w") as f: f.write('\\n'.join(lines))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM