slightly OT: Python BootCamp
Neil Cerutti
neilc at norwich.edu
Fri Dec 4 10:57:31 EST 2009
On 2009-12-04, Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:
> How would I re-write this? Just get rid of the try block and
> add a close:
>
> for (exten, list) in files.iteritems():
> f=open('extensions-%s.txt' % exten,'w')
> f.write('\n'.join(list))
"\n".join is a cute shortcut, but if you use it you must remember
to write the last, trailing '\n' manually.
> That's still not quite "best practice" -- best practice would
> be to use a with block, but (to my shame) I'm not entirely
> familiar with that so I'll leave it for others.
from __future__ import with_statement
# Etc.
for (exten, list) in files.iteritems():
with open('extensions-%s.txt' % exten,'w') as f:
f.write('\n'.join(list))
f.write('\n')
--
Neil Cerutti
More information about the Python-list
mailing list