[Tutor] Example for read and readlines()

Steven D'Aprano steve at pearwood.info
Sun Nov 11 04:40:49 EST 2018


On Sun, Nov 11, 2018 at 12:19:36PM +0530, Asad wrote:
> Hi All ,
> 
>          If I am loading a logfile what should I use from the option 1,2,3

Depends what you want to do. I assume that the log file is formatted 
into lines of text, so you probably want to iterate over each line.

with open(filename, 'r') as f:
    for line in f:
        process(line)

is the best idiom to use for line-by-line iteration. It only reads each 
line as needed, not all at once, so it can handle huge files even if the 
file is bigger than the memory you have.


> f3 = open ( r"/a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log", 'r' )

Don't use raw strings r"..." for pathnames.


> 1) should only iterate over f3
> 
> 2) st = f3.read()

Use this if you want to iterate over the file character by character, 
after reading the entire file into memory at once.

 
> 3) st1 = f3.readlines()

Use this if you want to read all the lines into memory at once.



-- 
Steve


More information about the Tutor mailing list