"file" does not work with the "with" statement!
Diez B. Roggisch
deets at nospam.web.de
Thu Dec 10 05:04:40 EST 2009
Michele Simionato wrote:
> I have just discovered that the syntax
>
> with file(name, 'w') as f:
> do_something(f)
>
> does not close the file at the end of the with statement! On the
> contrary
>
> with open(name, 'w') as f:
> do_something(f)
>
> works fine. The docs say "When opening a file, it’s preferable to use
> open() instead of invoking this constructor directly." but perhaps
> they should mention why :(
Are you sure? For me on python2.5, it works as advertised:
from __future__ import with_statement
def test(outf):
with outf:
outf.write("test\n")
try:
outf.write("test\n")
assert False, "Not closed"
except ValueError:
pass
outf = open("/tmp/foo", "w")
test(outf)
outf = file("/tmp/bar", "w")
test(outf)
Which Python do you use?
Diez
More information about the Python-list
mailing list