I want to read huge text file line by line (and stop if a line with "str" found). How to check, if file-end is reached?
fn = 't.log' f = open(fn, 'r') while not _is_eof(f): ## how to check that end is reached? s = f.readline() print s if "str" in s: break
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. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.
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.
There's no need to check for EOF in python, simply do:
with open('t.ini') as f: for line in f: # For Python3, use print(line) print line if 'str' in line: break
Why the with
statement:
It is good practice to use the
with
keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.
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