Delete file if exist

hey guys,

How do I delete a file if it exists?

Cheers.
chippedAsked:
Who is Participating?
 
peprCommented:
Actually, it should be os.remove(filename) -- see http://docs.python.org/library/os.html#os.remove. You may want to use it also without the try/except...

    if os.path.isfile(filename):
        os.remove(filename)

Open in new window


See the http://docs.python.org/library/os.path.html#os.path.isfile
Still, the os.remove() may fail (e.g. for files marked as read-only or if you do not have the right to delete), and you may want to test if this happened.  On the other hand, you should not overcomplicate your code.

Also, there is no need to use the semicolon in the above Python code.
0
 
HonorGodSoftware EngineerCommented:

import os;

try :
  remove( filename );
except :
  pass;

Open in new window

0
 
HonorGodSoftware EngineerCommented:
sigh,,  pepr, of course, you are correct. ;-)  Thanks for catching that.
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
chippedAuthor Commented:
Thank you guys :)
0
 
chippedAuthor Commented:
Could you guys pop back in here when you have a chance http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_26852254.html#a35013581

I've pretty much got it all working, just one little kink.

thanks.
0
 
HonorGodSoftware EngineerCommented:
Thanks for the assist, and the points.

Good luck & have a great day.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.