Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read two lines from a file at a time using python

Tags:

python

I am coding a python script that parses a text file. The format of this text file is such that each element in the file uses two lines and for convenience I would like to read both lines before parsing. Can this be done in Python?

I would like to some something like:

f = open(filename, "r") for line in f:     line1 = line     line2 = f.readline()  f.close 

But this breaks saying that:

ValueError: Mixing iteration and read methods would lose data

Related:

  • What is the most “pythonic” way to iterate over a list in chunks?
like image 219
Daniel Avatar asked Nov 01 '09 14:11

Daniel


1 Answers

Similar question here. You can't mix iteration and readline so you need to use one or the other.

while True:     line1 = f.readline()     line2 = f.readline()     if not line2: break  # EOF     ... 
like image 162
robince Avatar answered Sep 21 '22 05:09

robince