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?
"The readlines() method now returns an iterator, so it is just as efficient as xreadlines() was in Python 2".
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.
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.
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
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