Delete file if exist

hey guys,

How do I delete a file if it exists?

Who is Participating?
Actually, it should be os.remove(filename) -- see You may want to use it also without the try/except...

    if os.path.isfile(filename):

Open in new window

See the
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.
HonorGodSoftware EngineerCommented:

import os;

try :
  remove( filename );
except :

Open in new window

HonorGodSoftware EngineerCommented:
sigh,,  pepr, of course, you are correct. ;-)  Thanks for catching that.
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 :)
chippedAuthor Commented:
Could you guys pop back in here when you have a chance

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

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

Good luck & have a great day.
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.