How to Delete a File or Folder in Python?

How to Delete a File or Folder in Python?

Answer: To delete a file in Python you can use the os.remove() function.

Deleting files and folders is an essential operation to manage the files. Python provides multiple ways to remove files and folders efficiently. This blog explores the methods to delete files and folders in Python.

Table of Contents:

Methods to Delete a File or Folder in Python

Python provides various methods to delete a file or folder in Python. Following are some of these methods explained with examples:

Method 1: Using os.remove() to Delete a File in Python

The os.remove() function deletes a specified file from the file system.

Example:

Python

Output:

Explanation:

The os.remove(file_path) deletes the specified file and print() confirms that the file was deleted.

Method 2: Using os.rmdir() to Delete an Empty Folder in Python

The os.rmdir() function removes an empty folder. It can delete only those folders which do not contain any files or subfolders.

Example:

Python

Output:

Explanation:

The os.rmdir(folder_path) removes the empty folder print() confirming the folder was deleted.

Method 3: Using the shutil Module to Delete a Folder and its Contents in Python

The shutil module provides the rmtree() method to delete a folder along with all its files and subfolders.

Example:

Python

Output:

Explanation:

The shutil.rmtree(folder_path) deletes the folder along with all the files and folders inside it and the print() confirms the operation was successful.

The path.unlink() function from pathlib deletes a file present in the folder.

Example:

Python

Output:

Explanation:

The file_path.unlink() deletes the specified file present inside the folder by only specifying the file name and print()  confirms the deletion.

Method 5: Using path.rmdir() to Delete an Empty Folder in Python

The path.rmdir() function deletes an empty folder using the pathlib. This function works only for the folders which do not contain any files.

Example:

Python

Output:

Explanation:

The folder_path.rmdir() deletes the empty folder and the print() confirms the deletion of the folder

Conclusion

All these methods allow efficient file and folder deletion in Python. Use os.remove() for files and os.rmdir() for empty folders. The shutil.rmtree() is the optimal choice for deleting the entire folder along with the contents. Understanding these approaches allows you to process the text data effectively.

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner