How to delete a file or folder in Python

share link

by dot icon Updated: Jul 24, 2023

technology logo
technology logo

Guide Kit Guide Kit  

In Python, a "delete file" refers to removing a file from the file system. The delete file operation is used to delete a file from a storage device, such as a hard or solid-state drive. Deleting a file frees up disk space and removes the file's entry from the file system. This makes it inaccessible through normal file operations.  


Python provides several ways to delete files. The most used method is by utilizing the OS module. This method provides a range of operating system-related functionalities. The OS module includes a function called remove (), which allows you to delete a file using its file path. Python provides several methods and libraries for handling file operations, including deleting files. Let's discuss the different types of files that can be deleted using Python.  

Types of files deleted by Python:  

  • Deleting a Single File - You can use the os.remove() function from the built-in OS module to delete a single file.  
  • Deleting Many Files - If you want to delete many files, use the glob module or os.listdir() function.  
  • Deleting Files in a Directory - If you want to delete all files within a directory. you can use os.listdir() in combination with os.remove().  
  • Deleting Files - If you want to delete files, including files in subdirectories. You can use the shutil module's rmtree() function.  


In Python, there are several ways to delete files. The two most used approaches are using the os module's functions. This is also utilizing third-party libraries such as shutil.  


Let's discuss each method in more detail.  

  • Using the OS module - To delete a file using this module, you can use the os.remove() function.  
  • Using the shutil module - It includes a function called shutil.rmtree(). This function allows you to delete both files and directories.  


Also, to these methods, other specialized libraries and modules are available. That offers file deletion capabilities. For instance, the send2trash library provides a cross-platform solution. This is used for moving files and folders to the recycle bin or trash. That offers an extra level of safety when deleting files.  


The "delete" command is not standard in most operating systems. The "rm" command removes (deletes) files or directories from a file system.  


Here are some used parameters with the "rm" command:  

  • -f or --force - This forces the removal of files without prompting for confirmation. Even if the file is write-protected or the user does not have enough permissions.  
  • -r or -R or --recursive - This parameter deletes directories and their contents.  
  • -i or --interactive - This parameter prompts for confirmation before deleting each file.  
  • -v or --verbose - This displays detailed information about the files being deleted.  
  • --preserve-root - This is specific to some systems' "rm" command. It is done particularly with the root directory ("/").  


Here are some tips for using the delete command to delete files. It includes utilizing wildcards and specifying a time limit for the deletion process:  

  • Be cautious with the delete command. 
  • Use wildcards to specify file patterns.  
  • Use the recursive flag for deleting directories.  
  • Specify a time limit for the deletion process.  

Deleting files can be frustrating and lead to data loss. To avoid such situations, here are some practical tips. Also, to ensure the safety of your important data:  

  • Back up your files: Establish a backup routine and create copies of your important files. It is done on a separate storage device or cloud service.  
  • Use version control systems: This provides a layer of protection. This is provided against accidental deletions.  
  • Enable file recovery options: Many operating systems and file management tools offer features. This is used to recover deleted files.  
  • Be cautious with shortcuts and hotkeys: Take extra care when using these shortcuts. This is done when dealing with important files.  
  • Double-check before deleting: Develop a habit of double-checking before deleting files.  
  • Organize your files: Maintain a well-organized file structure to help prevent accidental deletions.  
  • Use file recovery software: Tools like Recuva, EaseUS Data Recovery Wizard, or PhotoRec. This can assist in recovering deleted files from storage devices.  
  • Educate and train yourself: Understanding how to handle and recover deleted files. It will empower you to avoid accidental deletions.  

Error handling:  

  • It suggests using exception-handling techniques to catch and handle potential errors. Those errors may occur during the file deletion process.  
  • This ensures that the program continues to run even if certain files cannot be deleted.  


In conclusion, this essay has explored the various aspects of Python tools. It highlights its unique features and capabilities. We began by discussing the increasing popularity of Python as a programming language. It is versatile in various domains. We then delved into the specific tool at hand. Its main purpose is to streamline and enhance the development process. This Python tool stands out due to its interface and extensive library support. It is compatible with many programming paradigms. It emphasizes code readability, maintainability, and robust debugging and testing capabilities. By leveraging these unique aspects, developers can streamline their development process. Developers can create high-quality software and achieve their programming goals more.  

Here is an example of deleting a file or folder in Python.

Fig1: Preview of the Code

Fig2: Preview of the folder before the code was run.

Fig3: Preview of the folder after the code was run.


In this solution, we are delete a file or folder in Python.


Follow the steps carefully to get the output easily.

  1. Install Jupyter Notebook on your computer.
  2. Open the terminal and import os by writing - import os
  3. Copy the snippet using the 'copy' button and paste it into that file.
  4. Remove the second and the third line of the code to avoid any error.
  5. Replace 'i' in os.remove(i) with the absolute path of the file you want to delete.
  6. Run the file using run button.

I hope you found this useful. I have added the version information in the following sections.

I found this code snippet by searching for "How to delete a file or folder in Python" in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in Python3.9.6.

Using this solution, we are able to delete a file or folder in Python

This process also facilities an easy to use, hassle free method to create a hands-on working version of code which would help us to delete a file or folder in Python


  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page.


1. How do I use Python to get a file?  

You can use Python to get a file using the urllib module or the requests library. It sends an HTTP request to a server and retrieves the file.  


Here's an example using both approaches:  

  • Using urllib module - import urllib.request.  
  • Using requests library - import requests.  


2. What is the best way to delete files using Python?  

In Python, you can delete files using the OS or shutil modules. Both modules provide functions to perform file operations, including deleting files.  


Here's how you can delete files using each module:  

  • Using the OS module.  
  • Using the shutil module.  


In the OS module, the os.remove() function deletes a single file specified by its path. But the shutil.rmtree() function is used to delete both files and directories. It removes the entire directory tree at the given path. It includes all its files and subdirectories.  


3. What is the file operation module in Python Programming?  

The file operation module is the functionality provided by the built-in "os" and "shutil". It helps perform various file-related operations. These modules allow you to work with files and directories. It includes creating, reading, writing, moving, copying, and deleting them.  


The "os" module: The "os" module provides various functions. It helps in interacting with the operating system. Some used functions from this module are:  

  1. os.path.exists(path)  
  2. os.path.isfile(path)  
  3. os.path.isdir(path)  
  4. os.listdir(path)  
  5. os.mkdir(path)  
  6. os.remove(path)  
  7. os.rename(src, dst)  


The "shutil" module: It provides higher-level file operations and extra file-related utilities. Some used functions from this module are:  

  1. shutil.copy(src, dst)  
  2. shutil.copytree(src, dst)  
  3. shutil.move(src, dst)  
  4. shutil.rmtree(path)  
  5. shutil.chmod(path, mode)  

4. Is there a library available for file operations with Python?  

Yes, there are several libraries available for file operations in Python. The most used library is the built-in OS module. It provides various functions for interacting with the operating system, including file operations.  


5. How can I analyze files in different formats using Python?  

You can use various libraries and modules to analyze files in different formats. It provides functionalities for reading and manipulating different file formats.  


Here are some used libraries for file analysis in Python:  

  • CSV (Comma-Separated Values)  
  • Excel  
  • JSON (JavaScript Object Notation)  
  • XML (eXtensible Markup Language)  
  • PDF (Portable Document Format)  
  • Text Files  
  • Image Files  
  • Audio Files  
  • SQLite Databases