[英]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:需要注意的几点:
b
is for opening a file in binary mode. b
用于以二进制模式打开文件。 You don't need this since you are working with text files. 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.