Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to mix readline() and line iterators in python file processing?

Tags:

python

file-io

Is it safe to read some lines with readline() and also use for line in file, and is it guaranteed to use the same file position?

Usually, I want to disregard the first line (headers), so I do this:

FI = open("myfile.txt")
FI.readline()             # disregard the first line
for line in FI:
    my_process(line)
FI.close()

Is this safe, i.e., is it guaranteed that the same file position variable is used while iterating lines?

like image 335
highBandWidth Avatar asked Jan 21 '11 18:01

highBandWidth


People also ask

Is readline an iterator?

"The readlines() method now returns an iterator, so it is just as efficient as xreadlines() was in Python 2".

How is method readline () different from Readlines () in Python?

What is Python readline()? Python readline() method will return a line from the file when called. readlines() method will return all the lines in a file in the format of a list where each element is a line in the file.

How many parameter's does readline () takes?

readline() function reads a line of the file and return it in the form of the string. It takes a parameter n, which specifies the maximum number of bytes that will be read. However, does not reads more than one line, even if n exceeds the length of the line.


1 Answers

No, it isn't safe:

As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right.

You could use next() to skip the first line here. You should also test for StopIteration, which will be raised if the file is empty.

with open('myfile.txt') as f:
    try:
        header = next(f)
    except StopIteration as e:
        print "File is empty"
    for line in f:
        # do stuff with line
like image 138
Simon Whitaker Avatar answered Nov 15 '22 03:11

Simon Whitaker