[IPython-user] Files not closed under IPython?

Fernando Perez Fernando.Perez at colorado.edu
Sun Sep 17 17:13:08 CDT 2006


Please note that you'll need to be subscribed to post to the list


ipython-user-bounces at scipy.org wrote:

> For the simple script below, the results are different when running
> within IPython than for CPython as shown.  Is this behavior expected?
> Is there a way to force the same behavior when running under IPython?
> 
>    Mike
> 
> ------------------------------
> 
> import csv
> 
> try:
>     writer = csv.writer(open('test.csv', 'a'))
>     writer.writerow([1,2,3])
>     print "file written"
> except:
>     print "couldn't open file"
> 
> ------------------------------
> 
> Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)]
> Type "copyright", "credits" or "license" for more information.
> 
> IPython 0.6.13 -- An enhanced Interactive Python.
> ?       -> Introduction to IPython's features.
> %magic  -> Information about IPython's 'magic' % functions.
> help    -> Python's own help system.
> object? -> Details about 'object'. ?object also works, ?? prints more.
> 
> In [1]: cd e:/projects/python/misc/
> e:\projects\python\misc
> 
> In [2]: ls *.csv
>  Volume in drive E is New Volume
>  Volume Serial Number is 18AE-A27A
> 
>  Directory of e:\projects\python\misc
> 
> File Not Found
> 
> In [3]: !python writecsv.py
> file written
> 
> In [4]: !type test.csv
> 1,2,3
> 
> In [5]: !del test.csv
> 
> In [6]: ls *.csv
>  Volume in drive E is New Volume
>  Volume Serial Number is 18AE-A27A
> 
>  Directory of e:\projects\python\misc
> 
> File Not Found
> 
> In [7]: run writecsv
> file written
> 
> In [8]: !type test.csv
> 
> In [9]: ls *.csv
>  Volume in drive E is New Volume
>  Volume Serial Number is 18AE-A27A
> 
>  Directory of e:\projects\python\misc
> 
> 09/16/2006  12:22 PM                 0 test.csv
>                1 File(s)              0 bytes
>                0 Dir(s)  115,079,897,088 bytes free
> 
> In [10]: !del test.csv
> e:\projects\python\misc\test.csv
> The process cannot access the file because it is being used by another process.

You need to close your file descriptors yourself, python doesn't guarantee 
their closing at any particular time other than the interpreter's exit.  Since 
in ipython, the python process hasn't died yet, your files aren't closed. 
When you start a fresh python process from the command line, that process 
finishes and all open files get closed.

Get in the habit of closing any open files when you're done with them, if you 
want to avoid all kinds of hard-to-track bugs.  This is not an ipython issue.

Regards,

f


More information about the IPython-user mailing list