[Tutor] Reset while loop

Alan Gauld alan.gauld at btinternet.com
Thu May 7 00:40:39 CEST 2009


"David" <david at abbottdavid.com> wrote

> Alan, thanks for your time and great tips :)

You're welcome, I was in a hurry so wasn't sure I understood fully.

> Here is what I came up with;
>
> def print_log_end(fname, bufsize, linesep):
>     f = open(fname, 'r')
>     f.seek(-bufsize, os.SEEK_END)    # goto one buffsize away from end
>     log = f.read().split(linesep)[-8:]
>     for i in log:
>            print i
>     f.close()
>
> def print_tail(fname, bufsize, linesep):
>     f = open(fname, 'r')
>     f.seek(-bufsize, os.SEEK_END)    # goto one buffsize away from end
>     return f.read().split(linesep)[-2:]
>     f.close()

One of the key principles of programming is DRY:
Don't Repeat Yourself.

Where you see 2 functions with near identical code look to
see how you can combine them or reuse one of them.

In the case above if you make print_tail(*) take a numlines
parameter you can reuse it in print_log_end.

(*)But you shout rename it since it doewsn't print it returns!
So call it get_tail() or similar...

So the functions become:

def print_log_end(fname, bufsize, linesep):
     for i in get_tail(fname, 8, bufsize, linesep):
            print i

 def print_tail(fname, numlines, bufsize, linesep):
     f = open(fname, 'r')
     f.seek(-bufsize, os.SEEK_END)    # goto one buffsize away from end
     result =  f.read().split(linesep)[-numlines:]
     f.close()
     return result

Note: The return needs to be after the close since othewise the close
won't get called explicitly - it is called implicitly by the file going out
of scope at the end of the function - and its good practice to explicitly
close the file

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list