Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: read all text file lines in loop

Tags:

python

file

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 
like image 330
Prog1020 Avatar asked Jul 30 '13 14:07

Prog1020


People also ask

How do you read all lines in a text file in Python?

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.

How do you read multiple lines from a text file in Python?

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.


1 Answers

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.

like image 50
Ashwini Chaudhary Avatar answered Sep 24 '22 20:09

Ashwini Chaudhary