| by Arround The Web | No comments

Python OS Remove

Python has multiple built-in modules to work with files and directories and to perform an operation on them. The “OS” module in Python is commonly used to interact with the operating system or to deal with the file handling operation. Removing files and directories from the specified path can be performed using the “os.remove()” method in Python. This method removes single or multiple files from the specified path/location. Other multiple modules such as shutil, pathlib, etc. can be utilized to delete/remove the files or directories in Python.

This article delivers an in-depth guide on the Python “os.remove()” method utilizing multiple methods. Here are the quick links::

What is the “os.remove()” Method in Python?

Alternative Method (pathlib Module) to Remove File in Python
Conclusion

 

What is the “os.remove()” Method in Python?

The “os.remove()” method in Python is utilized to remove/delete the file by taking the specified path as an argument. If the passed path is a directory then the OSError will be retrieved to the output. The permission denied error can also be retrieved while deleting the directory using the os.remove() method.

Syntax

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

 
Parameters

In the above syntax:

    • The “path” parameter indicates the path-like object that represents the complete path of the file.
    • The “*” parameter specifies that all parameters are keyword-only arguments.
    • The “dir_fd” parameter by default is “None”, it is a file descriptor that corresponds to a directory/folder.

Return Value

The “os.remove()” does not retrieve any value. It retrieves the “OSERROR” if the specified file is a directory and “FileNotFoundError” if the given file is not found.

Example 1: Removing File Using the “os.remove()” Method

Firstly, we create the text file named “example” at the specified path in the directory. Here is an example of file creation:


To remove this file in Python, take the below code:

# OS module Imported
import os

# Specify the File Path
filePath = r'C:\Users\p\Documents\program\example.txt'

# Delete/Remove the Specified File
os.remove(filePath)
print('Successfully Deleted!')

 
Here, we initially imported the “os” module. After that, the path is specified to the variable named “filepath”. Next the “os.remove()” method is used to remove the particular path and displays the message to the console.

Output


Example 2: Removing Multiple Files in Directory Using the “os.remove()” Method

This example removes multiple files from the specified directory using the “os.remove()” method. Let’s take the below files that are placed in the specified directory:


To remove all multiple files take the below code as an example:

# OS module Imported
import os

# Specify the directory Path
filepath = r'C:\Users\p\Documents\program'

# Specify the Files Name in the list
file1 = ["example.txt", "example1.txt", "example2.txt"]

# Delete/Remove the all Specified Files
for name in file1:
    file2 = os.path.join(filepath, name)
    os.remove(file2)
print('Successfully Deleted!')

 
In this code, the “os” module is imported. Next, we specify the path and multiple file names as a list. After that, the for loop is used to loop through the file and join all the files using the “os.path.join()” method. Lastly the “os.remove()” method is used to remove the files from the specified path.

Output


Example 3: Removing an Empty Directory Using the “os.rmdir()” Method

If the specified path is an empty directory then the “os.rmdir()” method of the “os” module is used in Python. Take this code as an example:

# OS module Imported
import os

# Specify the Path
directory = r"C:\Users\p\Documents\program\sample"

# Remove the Empty Directory
os.rmdir(directory)
print (" Successfully Removed!")

 
Here, the “rmdir()” method takes the complete path of the empty directory as an argument and removes the directory.

Output


Example 4: Removing a Non-Empty Directory Using the “shutil” Module

We can also remove the non-empty directory using the “shutil” module. For instance, take this code as an example:

# shutil module Imported
import shutil

# Specify the Path
directory = r"C:\Users\p\Documents\program\sample"

# Remove the Non-Empty Directory
shutil.rmtree(directory)
print ("Successfully Removed!")

 
In the above code, the “shutil” module is declared/imported at the start. Next, we specified the directory path to the variable named “directory”. Lastly, the “shutil.rmtree()” method of the “shutil” module is used to remove the non-empty directory.

Output


Example 5: Checking the Existence of the File Before Removing Using the “os.remove()” Method

We can also check the existence of the file before removing it to improve the efficiency of the program. Let’s consider the below code as an example:

# OS module Imported
import os

# Specify the File Path
filepath = r'C:\Users\p\Downloads\sample\example.txt'

# Remove Specified File
if os.path.exists(filepath):
  os.remove(filepath)
  print("Successfully Removed!")
else:
  print("File Does Not Exist!")

 
Here, we first import and specify the complete file path of the particular file. Next, the “if-else” statement is used to check the file’s existence and remove the file or display the appropriate message. If the file exists then the “os.remove()” method in the “if” block is used to remove the file, otherwise the “else” block shows the “File Does Not Exist” error.

Output

Alternative Method (pathlib Module) to Remove File in Python

Other methods can also be utilized in Python to remove the file or directory from the given path. The “pathlib” module is one of them that can be used to remove the file from Python. Take this code as an example:

# pathlib module Imported
from pathlib import Path

# Specify the File Path
file1 = Path(r"C:\Users\p\Documents\program\new.txt")

# Remove the File
file1.unlink()
print("Successfully Removed!")

 
Here, we import the “pathlib” module with the path constructor method. Next, the “Path()” method accepts the specified file path as an argument and returns the path object. After that, the “file.unlink()” method is used to remove the file.

Output

Conclusion

In Python, the “os.remove()” method is utilized to remove/delete the particular file or multiple files placed at the specified path. However, it cannot delete the directory without iterating over it. To remove the empty and non-empty folder/directory the “os.rmdir()” method of the “os” module and “shutil.rmtree()” method of the “shutil” module is used in Python. We can also remove the files from a particular location using the “pathlib” module in Python. This tutorial provided multiple ways with unique examples to remove files and directories in Python.

Share Button

Source: linuxhint.com

Leave a Reply