我正在尝试将两个文本文件组合在一起。第一个文件有两列,第二个文件有5列。以下是文件外观的示例:
FILE1.TXT
333333 1
423232 1
244311 2
333333 2
and so on...
FILE2.TXT
1 4 0 5 32
3 2 3 32 23
3 4 4 2 2
and so on ...
两个文件的行数相同。我想将file1.txt与file2.txt结合起来创建一个新的file3.txt,格式如下:
file3.txt
333333 1 1 4 0 5 32
423232 1 3 2 3 32 23
244311 2 3 4 4 2 2
and so on
我写了这个代码将file1.txt和file2.txt合并在一起。但是,我得到的是一个文件,它在file1.txt的末尾添加了file2.txt的内容,这不是我想要的。我得到这样的东西:
333333 1
423232 1
244311 2
333333 2
1 4 0 5 32
3 2 3 32 23
3 4 4 2 2
这是我的代码:
filenames =['file1.txt','file2.txt']
with open('file3.txt', 'w') as outfile:
for x in filenames:
with open(x) as infile:
for line in infile:
outfile.write(line)
如何修复此代码,以便获取类似file3.txt的文件,即将file2.txt行添加到file1.txt的相应行?任何建议/帮助将不胜感激。谢谢!
答案 0 :(得分:5)
你可以试试这个:
在Python 3中:
with open('file3.txt', 'w') as file3:
with open('file1.txt', 'r') as file1:
with open('file2.txt', 'r') as file2:
for line1, line2 in zip(file1, file2):
print(line1.strip(), line2.strip(), file=file3)
如果要处理多个文件,可以将代码概括为:
filenames = ['file1.txt', 'file2.txt', ...]
with open('output.txt', 'w') as writer:
readers = [open(filename) for filename in filenames]
for lines in zip(*readers):
print(' '.join([line.strip() for line in lines]), file=writer)
在Python 2中:
with open('file3.txt', 'w') as file3:
with open('file1.txt', 'r') as file1:
with open('file2.txt', 'r') as file2:
for line1, line2 in zip(file1, file2):
print >>file3, line1.strip(), line2.strip()
希望它有用!