On 11/11/2018 10:04, Asad wrote:

> 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)

Yes, that woyuld be the best choice in that scenario.

> 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 .

In that case you could use readlines() if it is a small file.
Or you could save the last 5 lines and print those each time
you find an error line. You should probably write a function
to save the line since it needs to move the previous lines
up one.

buffer = ['','','','','']

def saveLine(line, buff):
    buff[0] = buff[1]
    buff[1] = buff[2]
    buff[2] = buff[3]
    buff[3] = buff[4]
    buff[4] = line

for line in file:
    saveLine(line,buffer)
    if error_condition:
       printBuffer()

readlines is simpler but stores the entire file in memory.
The buffer saves memory but requires some extra processing
to save/print. There are some modules for handling cyclic
stores etc but in a simple case like this they are probably
overkill.

> 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 .

textfile lines are defined by the existence of the \n
so both readlines() and a loop over the file will both
read multiple lines if a \n is missing.

You could use read() and a regex to check for some
text marker and insert the newlines. This would be best
if the whole file had them missing.

If it just an occasional line then you can iterate over
the file as usual and check each line for a missing \n and
insert (or split) as needed.

You might want to write the modified lines back to
a new file.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to