Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading n lines from file (but not all) in Python

Tags:

python

file

How to read n lines from a file instead of just one when iterating over it? I have a file which has well defined structure and I would like to do something like this:

for line1, line2, line3 in file:
    do_something(line1)
    do_something_different(line2)
    do_something_else(line3)

but it doesn't work:

ValueError: too many values to unpack

For now I am doing this:

for line in file:
    do_someting(line)
    newline = file.readline()
    do_something_else(newline)
    newline = file.readline()
    do_something_different(newline)
... etc.

which sucks because I am writing endless 'newline = file.readline()' which are cluttering the code. Is there any smart way to do this ? (I really want to avoid reading whole file at once because it is huge)

like image 734
Piotr Lopusiewicz Avatar asked Nov 29 '25 11:11

Piotr Lopusiewicz


1 Answers

Basically, your fileis an iterator which yields your file one line at a time. This turns your problem into how do you yield several items at a time from an iterator. A solution to that is given in this question. Note that the function isliceis in the itertools module so you will have to import it from there.

like image 111
neil Avatar answered Dec 01 '25 02:12

neil