Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is possible to iterate file by two lines? [duplicate]

Tags:

python

Possible Duplicate:
reading lines 2 at a time

In python we can iterate over file line by line. But what if i want iterate by two lines?

f = open("filename")
for line1, line2 in ?? f ??:
    do_stuff(line1, line2)
like image 370
kravemir Avatar asked Oct 30 '11 16:10

kravemir


People also ask

How do you iterate over two or more lists at the same time?

Iterate over multiple lists at a time We can iterate over lists simultaneously in ways: zip() : In Python 3, zip returns an iterator. zip() function stops when anyone of the list of all the lists gets exhausted. In simple words, it runs till the smallest of all the lists.

How do you read two lines in a text file in Python?

Method 1: fileobject.readlines() A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously.

Can you read a file multiple times in Python?

Python provides the ability to open as well as work with multiple files at the same time. Different files can be opened in different modes, to simulate simultaneous writing or reading from these files.

How do you traverse a line by line in Python?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list.


2 Answers

Use the grouper function from the itertools recipes.

from itertools import zip_longest

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(fillvalue=fillvalue, *args)


f = open(filename)
for line1, line2 in grouper(2, f):
    print('A:', line1, 'B:', line2)

Use zip instead of zip_longest to ignore an odd line at the end.

The zip_longest function was named izip_longest in Python 2.

like image 178
Petr Viktorin Avatar answered Oct 07 '22 15:10

Petr Viktorin


You could do something like this:

with open('myFile.txt') as fh:
  for line1 in fh:
    line2 = next(fh)

    # Code here can use line1 and line2.

You may need to watch for a StopIteration error on the call to next(fh) if you have odd lines. The solutions with izip_longest are probably better able to avoid that need.

like image 38
g.d.d.c Avatar answered Oct 07 '22 15:10

g.d.d.c