1

In Python 2.7 and later, one can use a solution like this to iterate over two files line by line. However, in earlier versions of Python this doesn't work and gives an invalid syntax error.

I was wondering about the best way to do this using Python 2.6?

Community
  • 1
  • 1
riklund
  • 1,031
  • 2
  • 8
  • 16

1 Answers1

1

The preferred way is still the same only, but with statement doesn't support multiple objects in a single statement. So, you might want to split it like this

from itertools import izip

with open("Input1.txt") as textfile1: 
    with open("Input2.txt") as textfile2:
        for x, y in izip(textfile1, textfile2):

According to the PEP-0343, "Specification: The 'with' Statement" section,

A new statement is proposed with the syntax:

   with EXPR as VAR:
       BLOCK

Here, with and as are new keywords; EXPR is an arbitrary expression (but not an expression-list) and VAR is a single assignment target. It can not be a comma-separated sequence of variables, but it can be a parenthesized comma-separated sequence of variables. (This restriction makes a future extension possible of the syntax to have multiple comma-separated resources, each with its own optional as-clause.)

thefourtheye
  • 233,700
  • 52
  • 457
  • 497