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.

Instructions

    • 1

      Make availability for your Python script using the command:

      import os

    • 2

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

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

    • 3

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

      os.unlink('filename')

Related Searches:

References

Resources

Comments

You May Also Like

Related Ads

Featured