10th Apr 2023 7 minutes read How to Delete a File in Python Xavier Rigoulet python Need to safely delete files and directories in Python? This article will show you how! How do you delete a file or a bunch of files programmatically? You can do so with the help of Python. In this article, we will cover how to delete a file, a batch of files, or a directory using Python. Let's get started – without deleting the root folder! But first, let’s answer a basic question: Why Use Python to Delete a File? Python provides a simple, powerful, and platform-independent way to delete files programmatically. If you do not know how to program in Python, I recommend you look at our Python programming track to start your journey. Using Python to delete files can be advantageous for several reasons: Cross-platform compatibility: Python can be run on multiple platforms (Windows, Linux, MacOS, etc.), and the same code can be used to delete files on any of these platforms. Easy to learn: Python is a beginner-friendly programming language with a relatively simple syntax, making it easy for new programmers to learn and use. Powerful libraries: Python has a vast library of pre-built modules that can simplify file operations, including file deletion. These modules can save you time and effort by providing high-level abstractions for complex file operations. Error handling: Python provides robust error handling mechanisms that can help prevent data loss or corruption due to file deletion errors. Scripting: Python is a popular scripting language; its ability to automate file deletion tasks can benefit system administrators and data analysts who need to perform routine file deletion tasks. In summary, using Python to delete files can save time and effort while ensuring cross-platform compatibility and robust error handling. Additionally, the language's scripting capabilities make it well-suited for automating file deletion tasks. Let's write some code that you can store as a Python file (.py) and run from your terminal when you need to delete files. 2 Ways to Delete a File in Python 1. Using os.remove() You can delete a file using Python’s os module, which provides a remove() function that deletes the specified file. As you can see, it’s quite straightforward. You simply supply the file path as an argument to the function: >>> import os >>> # path of the file to be deleted >>> file_path = "/path_to_folder/example1.txt" >>> # delete the file >>> os.remove(file_path) If the specified file does not exist, the remove() function raises a FileNotFoundError exception. Therefore, checking if the file exists before attempting to delete it is good practice. You can use the os.path.exists() function to check if a file exists. Here's an example. >>> import os >>> file_path = "/path_to_file" >>> if os.path.exists(file_path): ... os.remove(file_path) ... else: ... print("File not found.") 2. Using os.unlink() The os.unlink() function is another way to delete a file in Python. It is a synonym for the os.remove() function and behaves similarly. Here’s an example of how to use this function: >>> import os >>> # absolute path of the file to be deleted >>> file_path = "/path_to_folder/example2.txt" >>> # delete the file >>> os.unlink(file_path) Again, it's a good practice to check if the file exists before attempting to delete it. You can use the os.path.exists() function. >>> import os file_path = "/path_to_file" >>> if os.path.exists(file_path): ... os.unlink(file_path) ... else: ... print("File not found.") Note that os.unlink() function is only available in Unix-based systems like Linux or macOS; it may not work in Windows systems. In Windows, you can use os.remove() instead. How to Delete a Directory in Python In Python, you can also delete a directory using the pathlib module, which provides an object-oriented way of working with file system paths. Here are some examples of deleting a directory in Python using pathlib. First, let’s delete an empty directory: >>> import pathlib >>> # create a Path object for the directory to be deleted >>> dir_path = pathlib.Path("empty_dir") >>> # delete the directory >>> dir_path.rmdir() In this example, the rmdir() method deletes the empty directory specified by the dir_path object. To delete a non-empty directory, you can use the following example. >>> import shutil >>> import pathlib >>> # create a Path object for the directory to be deleted >>> dir_path = pathlib.Path("/path_to_my_dir/") >>> # delete the directory and its contents recursively >>> shutil.rmtree(dir_path) In this example, the rmtree() function from the shutil module is used to delete the non-empty directory specified by the dir_path object. The rmtree() function deletes the directory and all its contents recursively. Note that pathlib.Path.rmdir() can only delete empty directories. If the directory contains files or other directories, you need to use shutil.rmtree() to delete the directory and its contents recursively. Also, be careful when using shutil.rmtree(). It deletes all the contents of the directory – including files, subdirectories, and their contents – and cannot be undone. Deleting Multiple Files in Python In Python, you can delete multiple files using various methods. The method you choose will depend on your use case. We can use a loop to delete files iteratively: >>> import os >>> # directory containing the files to be deleted >>> dir_path = "/path_to_directory" >>> # list of file names to be deleted >>> file_names = ["file1.txt", "file2.txt", "file3.txt"] >>> # loop over each file name and delete the file >>> for file_name in file_names: . . . file_path = os.path.join(dir_path, file_name) . . . os.remove(file_path) In this method, a loop is used to iterate over each file name in the list and delete the file using the os.remove() function. Alternatively, it is also possible to use a list comprehension to delete files to achieve the same result. We can also use the glob module to delete files: >>> import glob >>> import os >>> # directory containing the files to be deleted >>> dir_path = "/path/to/directory" >>> # pattern for file names to be deleted >>> file_pattern = "*.txt" >>> # get a list of file paths using the glob module >>> file_paths = glob.glob(os.path.join(dir_path, file_pattern)) >>> # loop over each file path and delete the file >>> for file_path in file_paths: . . . os.remove(file_path) In this method, the glob module is used to get a list of file paths that match a specified pattern using the glob.glob() function. The list of file paths is then passed to a loop that deletes each file using the os.remove() function. In all these methods, it's important to check if the file exists before attempting to delete it. Using pathlib to Work with Files pathlib is a module in Python's standard library that provides an object-oriented approach to working with files and directories. The Path class in pathlib can be used to delete files using the unlink() method. Here’s an example: >>> from pathlib import Path >>> # path to the file to be deleted >>> file_path = Path("/path_to_file.txt") >>> # delete the file using the unlink() method >>> file_path.unlink() In this example, the Path class is used to create a Path object representing the file to be deleted. The unlink() method is then called on the Path object to delete the file. Note that the unlink() method will raise a FileNotFoundError if the file does not exist, so it's a good idea to check if the file exists before attempting to delete it. To delete multiple files using pathlib, you can use a loop or a list comprehension to iterate over a list of Path objects representing the files to be deleted. Here's an example using a loop: >>> from pathlib import Path >>> # list of file paths to be deleted >>> file_paths = [Path("/path/to/file1.txt"), Path("/path/to/file2.txt"), Path("/path/to/file3.txt")] >>> # delete each file using a loop >>> for file_path in file_paths: ... file_path.unlink() In this example, a list of Path objects representing the files to be deleted is created, and a loop is used to iterate over each file path and delete the corresponding file using the unlink() method. Just like with the os.remove() function, using Path.unlink() to delete files can result in data loss. Double-check that you're deleting the correct files before running your code. I did not explicitly state any particular way to end a script in this article. In the example above, all the lines are executed; however, feel free to read more about the multiple ways to end a script in Python. Beyond Deleting Files in Python In this article, we learned various ways of deleting files and directories in Python using fundamental Python packages. To strengthen your knowledge, feel free to check out our course on working with files and directories in Python. If you are looking for more ways to practice Python, you can also go through our common interview questions. And don’t forget to regularly visit LearnPython.com to keep learning. Tags: python