"file" does not work with the "with" statement!

Peter Otten __peter__ at web.de
Thu Dec 10 04:59:03 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?

Python 2.6.4 (r264:75706, Nov  2 2009, 14:44:17)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> with file("tmp.txt", "w") as f:
...     print >> f, "whatever"
...
>>> f.write("something")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file

Peter



More information about the Python-list mailing list