在python中迭代两个文本文件

在python中迭代两个文本文件,python,iteration,text-files,Python,Iteration,Text Files,我有两个文本文件,我想同时迭代这两个文件 i、 e: 文件1: x1 y1 z1 A,53,45,23 B,65,45,32 x2 y2 z2 A,0.6,0.9,0.4 B,8.6,1.0,2.3 文件2: x1 y1 z1 A,53,45,23 B,65,45,32 x2 y2 z2 A,0.6,0.9,0.4 B,8.6,1.0,2.3 我希望同时使用两个文件中的值: e、 g: 如何使用Python实现这一点?您需要将这两个文件视为迭代器并压缩它们。I

我有两个文本文件,我想同时迭代这两个文件

i、 e:

文件1:

  x1 y1 z1
A,53,45,23
B,65,45,32
  x2 y2  z2  
A,0.6,0.9,0.4
B,8.6,1.0,2.3
文件2:

  x1 y1 z1
A,53,45,23
B,65,45,32
  x2 y2  z2  
A,0.6,0.9,0.4
B,8.6,1.0,2.3
我希望同时使用两个文件中的值:

e、 g:


如何使用Python实现这一点?

您需要将这两个文件视为迭代器并压缩它们。Izip将允许您以惰性方式读取文件:

from itertools import izip

fa=open('file1')
fb=open('file2')
for x,y in izip(fa, fb):
    print x,y
现在已经有了成对的行,您应该能够根据需要解析它们并打印出正确的公式。

Python的内置函数非常适合:

>>> get_values = lambda line: map(float, line.strip().split(',')[1:])
>>> for line_from_1,line_from_2 in zip(open('file1'), open('file2')):
...     print zip(get_values(line_from_1), get_values(line_from_2))
...     print '--'
... 
[]
--
[(53.0, 0.6), (45.0, 0.9), (23.0, 0.4)]
--
[(65.0, 8.6), (45.0, 1.0), (32.0, 2.3)]
--
>>> 
因此,您应该能够按照自己的意愿使用这些值。大概是这样的:

  print sum([x * y for x,y in zip(get_values(line_from_1), get_values(line_from_2))])
我得到这个结果:

81.5

677.6


这对我来说很有用:

with open("file1.txt") as f1, open("file2.txt") as f2:
    # Ignore header line and last newline
    files = f1.read().split("\n")[1:-1]
    files += f2.read().split("\n")[1:-1]

# Split values and remove row name from lists
# string -> float all values read
a1, a2, b1, b2 = (map(float, elem.split(",")[1:]) for elem in files)

# Group by row
a = zip(*[a1, b1])
b = zip(*[a2, b2])

c1 = sum(e1 * e2 for e1, e2 in a)
c2 = sum(e1 * e2 for e1, e2 in b)
然后结果

>>> print c1
81.5
>>> print c2
677.6
编辑:如果您的Python版本不支持巫术,您可以执行以下操作:

# Open files, dont forget to close them!    
f1 = open("file1.txt")
f2 = open("file2.txt")

# Ignore header line and last newline
files = f1.read().split("\n")[1:-1]
files += f2.read().split("\n")[1:-1]

f1.close()
f2.close()

如果以同步所有数据为例,则使用
(i)zip提供的所有示例都可以正常工作。如果它们不同步(有时从其中一个读取的行比另一个多),那么
next()
函数就是您的朋友。使用它,您可以设置迭代器,然后在程序流中随时从其中任何一个请求新行。

请注意,在Python 2中,这将返回一个列表,而不是迭代器。这意味着,代码将在Python2.x.Correct下一次性读取整个文件。对于这样小的文件,这不太可能是个问题。但值得注意的是,在Python3中,内置函数
zip
也有同样的作用。