[英]concatenate two txt files
我是 python 的初学者,我有两个空格分隔的文本文件,第一个看起来像:
a b c
d e f
第二个看起来像:
1 2 3
4 5 6
我想垂直连接它们,这样 output 就是:
a b c
d e f
1 2 3
4 5 6
我怎样才能使用 python 做到这一点? 如果我想水平连接,它看起来像这样:
a b c 1 2 3
d e f 4 5 6
我该怎么做呢?
也许是这样的,使用join() :
with open("File1", 'r') as f:
file1 = f.read().split("\n")
with open("File2", 'r') as f:
file2 = f.read().split("\n")
vertically = "\n".join(file1 + file2)
print(vertically)
horizontally = "\n".join([" ".join(line) for line in zip(file1, file2)])
print(horizontally)
保存:
with open("File3.txt", 'w') as f:
f.write(vertically)
with open("File4.txt", 'w') as f:
f.write(horizontally)
对于第一个 output 这样的东西应该有效。
fin = open("File2.txt", "r")
data2 = fin.read()
fin.close()
fout = open("File1.txt", "a")
fout.write(data2)
fout.close()
对于第二个,你可以试试这个
file1 = open('myfile.txt', 'r')
Lines = file1.readlines()
对于这两个文件,然后在两个文件中合并索引 1,在两个文件中合并索引 2,并生成最终合并列表并将其写入文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.