Python Delete File

Python Delete File

If Python can create a file, it surely can delete one too! You can easily delete a file using the remove() function from the os module that comes built-in in Python.

You can delete a file as shown below.

Example

Python Delete File

Now, if the file does not exist at the specified path, Python will raise an error. To avoid the error, you can add the error handling block as below.

Example

Python Delete File-handling error

You can check the directory that you used to test the code above to see that the file is deleted! 

File handling and handling errors is generally a good practice to follow while coding. 

Tutorials for all brains!