[Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files.
Lie Ryan
lie.1296 at gmail.com
Sun Feb 28 16:38:58 CET 2010
On 03/01/10 01:12, Alan Gauld wrote:
>
>> def getLines(file):
>> """Get the content of a file in a lines list form."""
>> f = open(file, 'r')
>> lines = f.readlines()
>> f.close()
>> return lines
>
> I'm not sure these functions add enough value to ghave them. I';d
> probably just use
>
> try: open(outfile,'w').writelines(lines)
> except IOError: #handle error
>
> try: lines = open(filename).readlines()
> except IOError: #handle error
>
> The close will be done automatically since you don't hold a reference to
> the file
Remember why we have the new with-block? It's precisely because files
will be automagically closed only if we're running on CPython; Python
the language and thus alternative implementations doesn't guarantee
automatic closing. I'd agree with the function having minimal utility
value though:
with open(file) as f:
lines = f.readlines()
# f.close() will be called by the context manager
and if you're just copying to another file:
from contextlib import nested
with nested(open(infile), open(outfile, 'w')) as (fin, fout):
fout.write(fin.read())
or even better, as Alan suggested, using shutil.copyfile().
More information about the Tutor
mailing list