Hi All, thanks for the reply so to put into context say I have a file logfile formatted in text lines
1) and I want to extract the start time , error number and end time from this logfile so in this case what should I use I guess option 1 : with open(filename, 'r') as f: for line in f: process(line) should be fine or any other option ? 2) Another case is a text formatted logfile and I want to print (n-4) lines n is the line where error condition was encountered . 3) Do we need to ensure that each line in the logfile ends with \n . \n is not visible so can we verify in someway to proof EOL \n is placed in the file . Thanks, > > > > > > ---------- Forwarded message ---------- > From: Asad <asad.hasan2...@gmail.com> > To: tutor@python.org > Cc: > Bcc: > Date: Sun, 11 Nov 2018 12:19:36 +0530 > Subject: [Tutor] Example for read and readlines() > Hi All , > > If I am loading a logfile what should I use from the option 1,2,3 > > f3 = open ( r"/a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log", 'r' ) > > 1) should only iterate over f3 > > 2) st = f3.read() > Should iterate over st > > > 3) st1 = f3.readlines() > > Should iterate over st1 > > How are the above options different it they are not can there be some > examples to describe in which situations should we each method . > > > Thanks, > > -- > Asad Hasan > +91 9582111698 > > > > > ---------- Forwarded message ---------- > From: "Steven D'Aprano" <st...@pearwood.info> > To: tutor@python.org > Cc: > Bcc: > Date: Sun, 11 Nov 2018 20:40:49 +1100 > Subject: Re: [Tutor] Example for read and readlines() > 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 > > _______________________________________________ > Tutor maillist - Tutor@python.org > https://mail.python.org/mailman/listinfo/tutor > -- Asad Hasan +91 9582111698 _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor