在python中遍历两个文本文件 [英] Iterating over two text files in python

查看:92
本文介绍了在python中遍历两个文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个文本文件,我想同时遍历两个文件.

I have 2 text files and I want to iterate over both of them simultaneously.

即:

文件1:

  x1 y1 z1
A,53,45,23
B,65,45,32

文件2:

  x2 y2  z2  
A,0.6,0.9,0.4
B,8.6,1.0,2.3

我想同时使用两个文件中的值:

and I want use values from both files simultaneously:

例如:

c1 = x1*x2 + y1*y2 + z1*z2  #for first line
c2 = x1*x2 + y1*y2 + z1*z2  #for second line

如何使用Python做到这一点?

How can one do that using Python?

推荐答案

您需要将两个文件都视为迭代器并压缩它们. Izip将允许您以一种懒惰的方式读取文件:

You need to treat both files as iterators and zip them. Izip will allow you to read the files in a lazy way:

from itertools import izip

fa=open('file1')
fb=open('file2')
for x,y in izip(fa, fb):
    print x,y

现在您已经有了成对的线,您应该能够根据需要解析它们并打印出正确的公式.

Now that you've got pairs of lines, you should be able to parse them as you need and print out the correct formula.

这篇关于在python中遍历两个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆