Removing file in python

Python remove file — How to delete a file?

The files in Python are used for various purposes by the developers. After the developer has worked with the file, it is important to know how to delete it. For example in a large program, the developer would need to create files to store data but would not require them after the execution of the program. This is when deleting the file is a good idea and in this tutorial, we will discuss different ways to delete or remove a file in Python.
In this tutorial, we will discuss various methods to remove a file in Python using the os.remove() and the pathlib module. We will also discuss how to remove an empty and a non-empty directory in Python.

Table of contents

Removing file in Python using os.remove()

The OS module in Python provides functions for interacting with the operating system. This standard utility module provides a portable way of using operating system-dependent functionality. This module can remove a file or file path but cannot delete a directory. If the specified path is a directory, then the module will raise an OSError.

Syntax:

os.remove(path, *, dir_fd = None)

Case 1: To remove a file

Input:

import os file = 'file.txt' location = "/home/User/Documents" path = os.path.join(location, file) os.remove(path) print (“The file has been removed")

Output:

The file has been removed

In the above code snippet, we first specify which file we want to delete and where it’s located. Then, after joining, we use the os.remove() operation to delete it.

Case 2: The specified path is a directory

Input:

import os path = "/home/User/Documents/abcdef" os.remove(path) print (“The file has been removed")

Output:

Traceback (most recent call last): File "osremove.py", line 15, in os.remove(path) IsADirectoryError: [Errno 21] Is a directory: '/home/User/Documents/acdef'

Here, we do not need to use the ‘join’ operation as we directly specify the exact location. Make sure to import the OS library before using the os.remove() function.

Using the pathlib module to remove a file in Python

The pathlib module is very useful in removing or deleting a file in Python 3.4 or above. It is similar to the os.remove() and have to create a path object at first.

Input:

import pathlib p_obj = Path(".") type(p_obj) file = pathlib.Path("file_1/file.txt") file.unlink() 

When an instance of the Path class is created, a WindowsPath or PosixPath will be returned according to the machine you’re working on. And the unlink() function is used to remove the file or the symbolic link.

Removing empty directory

The above two approaches cannot be used to remove a folder. The os.rmdir() function in the OS module can delete an empty directory in Python.

Читайте также:  Setting Font Size

Input:

import os directory = "/home/User/Documents/abcdef" os.rmdir('directory') print (“The directory is removed.”)

Output:

The os.rmdir() function can only be used to delete an empty directory. If you specify a folder that contains files, the following error will be returned.

Input:

import os directory = "/home/User/Documents/abcdef/ghi" os.rmdir('directory')

Output:

Permission denied: '/home/User/Documents/abcdef/ghi' Directory 'ghi' can not be removed

Removing a non-empty directory

You can use the high-level file operation module, shutil to remove a file or collection of files. You can use this module in the same way as the os.rmdir() function but here you can also remove the non-empty directories. All the contents inside the directory are removed as well.

Input:

import shutil path = /home/User/Documents/abcdef shutil.rmtree('path') print (“All the files inside the directory are removed with the directory”)

Output:

All the files inside the directory are removed with the directory

Just remember that you cannot remove a single file with the shutil.rmtree() function. For deleting a single file, you can use the os.remove() function and the pathlib module that’s been illustrated above.

Closing thoughts

In Python, removing a file is a very common operation. The os.remove() function and the pathlib module can remove a single file. While the os.rmdir() function removes an empty directory and the shutil module removes the non-empty directory in Python. You can learn other Python concepts here.

Источник

How to Delete a File in Python

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:

  1. 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.
  2. 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.
  3. 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.
  4. Error handling: Python provides robust error handling mechanisms that can help prevent data loss or corruption due to file deletion errors.
  5. 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.

Читайте также:  Java jframe как закрыть

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.")

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.

Читайте также:  Get all cookies in javascript

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.

Источник

Оцените статью