Combining columns from two different text files in python
我正在尝试将两个文本文件组合在一起。第一个文件有两列,第二个文件有五列。以下是文件外观的示例:
文件1.TXT
1 2 3 4 5 | 333333 1 423232 1 244311 2 333333 2 and so on... |
文件2.TXT
1 2 3 4 | 1 4 0 5 32 3 2 3 32 23 3 4 4 2 2 and so on ... |
两个文件的行数相同。我想将file1.txt与file2.txt结合起来创建一个新的file3.txt,其格式如下:
文件3.TXT
1 2 3 4 | 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合并在一起,但是我得到的是一个文件,它将file2.txt的内容添加到file1.txt的末尾,这不是我想要的。我得到这样的东西:
1 2 3 4 5 6 7 | 333333 1 423232 1 244311 2 333333 2 1 4 0 5 32 3 2 3 32 23 3 4 4 2 2 |
这是我的代码:
1 2 3 4 5 6 | 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) |
如何修复此代码,以便获得文件3.txt,即将file2.txt的行添加到相应的file1.txt行中?如有任何建议/帮助,我们将不胜感激。谢谢!
您可以尝试以下操作:
在Python 3中:
1 2 3 4 5 | 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) |
如果要处理多个文件,可以将代码归纳为:
1 2 3 4 5 | 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中:
1 2 3 4 5 | 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() |
希望能有所帮助!