file2lines
François Pinard
pinard at iro.umontreal.ca
Tue Aug 1 09:04:06 EDT 2000
[Miki Tebeka]
> Is there a standard function that does something like this?
> def file2lines(file_name):
> lines = []
> try:
> fp = open(file_name)
> lines = fp.readlines()
> fp.close()
> except:
> pass # ignore errors
> return lines
> And then you can just:
> for line in file2lines('myfile'):
> some_interesting_function(line)
I always write directly:
for line in open('myfile').readlines():
some_interesting_function(line)
You can bury this within a `try...except' clause, of course, but I think
better to not blindly hide all errors, in general. If you stick to CPython
features, you'll get shorter, cleaner code! A consequence of this is that
you have a big gain in legibility (in my opinion).
--
François Pinard http://www.iro.umontreal.ca/~pinard
More information about the Python-list
mailing list