[Tutor] file enigma
spir
denis.spir at free.fr
Thu Jun 11 12:56:10 CEST 2009
Le Thu, 11 Jun 2009 10:21:31 +0100,
Tim Golden <mail at timgolden.me.uk> s'exprima ainsi:
> spir wrote:
> > Hello,
> >
> > text = file(filename).read()
> >
> > (or: open(filename).read())
> >
> > How do you close() the file? ;-)
>
> Well, in any version of Python, you can do this:
>
> <code>
> f = open (filename)
> text = f.read ()
> f.close ()
> </code>
>
> or, slightly more robsustly:
>
> <code>
> f = open (filename)
> try:
> text = f.read ()
> finally:
> f.close ()
> </code>
>
> But in Python 2.5+ that can be spelt:
>
> <code>
> with open (filename) as f:
> text = f.read ()
> </code>
>
>
> As it happens, in CPython at the moment, the file object will
> be closed when all references are released -- which would be
> at the end of the line in your example. I don't know whether
> that's guaranteed by the implementation, or merely the case
> at present. It's certainly *not* the case in other implementations,
> such as IronPython & Jython which don't use the same kind of
> refcounting.
Thank you, Tim, this really answers my question.
My question was motivated by 2 reasons:
* This "open(filename).read()" expression is very common, while there is seemingly no way to close the file. There's not even a way to check the flag file.closed, I guess!
* I intended to write a helper func "filetext(filename)" to open/read/close/return (or equivalent using the with idiom).
But if ever the expression above is rather safe, then there is no need for the said helper.
I also thought at str methods (where the target string is a filename) .filetext() and .filebytes (the latter with file opening in 'rb' mode).
Again, these methods would be useless if one can safely write "open(filename).read()".
> FWIW, in non-critical code I often use the style you illustrate
> above: text = open (filename).read (). But in production code,
> I usually use the with statement.
Right, thanks again.
> TJG
Denis
------
la vita e estrany
More information about the Tutor
mailing list