考虑以下两个文件:
FILE1.TXT:
    file1line1
    file1line2
    file1line3
FILE2.TXT
    file2line1
    file2line2
    file2line2
我想将file1中的每一行与file2中的相应行组合在一起.
怎么能在python中完成.
您可以假设两个文件中的行数相等.
有了zip()你可以很容易地做到这一点:
with open('file1.txt') as fh1, open('file2.txt') as fh2:
    for line1, line2 in zip(fh1, fh2):
        # line1 from file1, line2 from file2
如果您使用的是Python 2,则会将所有文件加载到内存中; 请itertools.izip()改用以根据需要读取行:
from itertools import izip
with open('file1.txt') as fh1, open('file2.txt') as fh2:
    for line1, line2 in izip(fh1, fh2):
        # line1 from file1, line2 from file2
在Python 3中,zip()表现为itertools.izip().
| 归档时间: | 
 | 
| 查看次数: | 104 次 | 
| 最近记录: |