How to Check If a File Exists and Then Delete It in Python


Python is a comprehensive, high-level programming language. When writing a Python script, you often need to work with files on the hard drive. Before deleting a file, you need to make sure that the file actually exists. Otherwise, your program gets terminated due to an exception (an error). A special Python module called "os" allows you to access required commands within your program.

  • Make availability for your Python script using the command:

    import os

  • Check if the file exists using the following "if" statement:

    if (os.path.exists('filename')):

  • Delete the file by adding the "unlink" command to the "if" statement:


Related Searches


Promoted By Zergnet



You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!