delete file

Peter Hansen peter at
Tue Jul 15 18:21:27 CEST 2003

lamar_air wrote:
> I am using this remove method and it works well as long as the file is
> there
>    os.remove("C:\Inetpub\wwwroot\Cgi-bin\output.txt")
> If the file doesn't exist then i get an error that the file is not
> found.  I want to stay away from using
>    f2=open('C:\Inetpub\wwwroot\Cgi-bin\output.txt', 'w') so how can i
> check if the file exists first?

I'm still confused.  You "want to stay away from using open(xx)"
but you are getting an error from os.remove when the file doesn't

Why do you want to stay away from open() when it would clearly fix
the problem?  It does not raise an exception when the file doesn't
exist, and it quietly truncates (effectively removes) the file when
it already does exist.

Anyway, if you insist on using os.remove(), just put it in a 
try/except OSError block and catch the exception that is thrown
when the file does not exist.

Alternatively, and the worst of all the solutions, is to use
os.path.exists() first to check if the file already exists, and
only then to call os.remove().

The choice is yours.  Personally, I'd go with open(xxx, 'w') since
that's safer, idiomatic (i.e. standard usage), and much simpler.


More information about the Python-list mailing list