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)
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With