How to Delete a File or Folder in Python 


               


How to Delete a File or Folder in Python



Python


In this article, we show how to delete a file or folder in Python.

In Python, it is relatively simple to delete a file or a folder.

We'll first go over how to delete a file. Then, we'll go over how to delete a folder.


How to Delete a File

The code to delete a file in Python is shown below.



So, first, we must import the os module.

The code above deletes the file, file.txt.

We use the os.unlink() function to delete a file. Inside of this os.unlink() function, you simply have to put the path to the file that you want to delete. If the file is in the current working directory, then all you have to do is put the filename. If not, you have to specify the full path.


How to Delete an Empty Folder (Directory)

Now, we'll show how to delete an empty folder, a folder that does not have any files or directories in it.

To delete an empty folder, you can use the os.rmdir() function.



This code, above, will delete the folder, PythonProjects (as long as the folder is empty).

If the folder contains any files at all, then an error will be thrown. You will get an OSError: [WinError 145] The directory is not empty. You may get a different error if not on a Windows computer.

But as long as the directory is empty, it will be deleted.


How to Delete an Directory (that has empty)

Now, we will show how to delete a directory that contains items (files or other directories).

We can do this through the shutil.rmtree() function.

This is shown in the code below.



The code above will now remove the folder, PythonProjects, even if it has items in it. The entire directory, including all items in the directory, will be deleted.

So, these are the various ways in which files and directories can deleted in Python.


Related Resources



HTML Comment Box is loading comments...