[Tutor] Add newline's, wrap, a long string

Alan Gauld alan.gauld at btinternet.com
Thu Apr 30 01:58:26 CEST 2009


"David" <david at abbottdavid.com> wrote 

> I don't know how else to describe it, that is so cool :)

:-)

Couple of comments below.

> import textwrap
> data = {'CBUILD':None, 'CFLAGS':None, 'MAKEOPTS':None}
> def get_use():
>     fname = open('/tmp/comprookie2000/emerge_info.txt')
>     for line in fname:
>         for keyphrase in data:
>             if keyphrase in line:
>                 output = line.split('"')[1]
>                 data[keyphrase] = textwrap.fill(output, 80)
>     fname.close()
> 
> get_use()

It would be better practice to put data inside the function 
and then return the result. Also I'd pass the filename into 
the function.

def get_use(fname):
      data = ....
      for line in open(fname):      
          ....
      return data

data = get_use('/tmp/foo/bar/baz.txt')

That makes the function, and therefore the module, more 
easily reusable and allows you to call the function several 
times on different files wityhout overwriting the results. 
You may not need to do that now but it might be useful 
in the future.

> CBUILD = data['CBUILD']
> CFLAGS = data['CFLAGS']
> MAKEOPTS = data['MAKEOPTS']

Don't bother storing in variables just use the dictionary 
directly in your print statements. Learn to love and use 
Python's collections. They are the secret of much of Python's 
power.

Just some thoughts,

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



More information about the Tutor mailing list