deleting os files

Peter Hansen peter at
Sun Nov 28 15:27:58 CET 2004

John Aherne wrote:
> Unfortunately, when it comes to delete, I get a permission error. And
> yes, when I run the program and try to delete the file from the
> command prompt, I get a permission error.

Usually posting actual tracebacks, or the actual error messages
from your console, is a very good idea.  One man's permission
error might be another's missing file, to paraphrase an old

> As far as I can tell, I assume the file is being kept open in the
> DictReader call. But I can't work out how I can close the file -
> .close comand also returns an error. I was assuming that on the return
> from the call the file would be closed - mistakenly I now think.

I don't believe csv Readers ever touch the file other than to read
from it.  But they do cache a reference to it, meaning that the
automatic closure which you've perhaps become used to from other
uses of files is no longer happening.  Deleting the Reader itself
might work, but it's not the "best" solution.

> The sample code is below. Not much to it. If I comment out the close
> and delete lines (not shown here) then the program happily carries on
> processing the same files over and over. Not what I want.

Unfortunately, without those lines, and without some idea of where
"csv_file" is being created/opened, the code isn't much help.

Please either post a more useful sample, or experiment with this:
maintain a reference to the csv_file object (I guess you have it
right there, but since I can't see where you opened that object
I don't know for sure what it actually is), and after you are
done reading from it, preferably in the "finally" stanza of a
try/finally block, do a csv_file.close().  This "should" work,
but without seeing more of your code it's really only a guess
on my part.


More information about the Python-list mailing list