The Wayback Machine - https://web.archive.org/web/20240722044711/https://www.geeksforgeeks.org/python-os-remove-method/
Open In App

Python | os.remove() method

Last Updated : 29 May, 2019
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.

All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.

os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method. os.rmdir() can be used to remove directory.

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

Parameter:
path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.
dir_fd (optional) : A file descriptor referring to a directory. The default value of this parameter is None.
If the specified path is absolute then dir_fd is ignored.

Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter.

Return Type: This method does not return any value.

Code #1: Use of os.remove() method to remove a file




# Python program to explain os.remove() method 
    
# importing os module 
import os
  
# File name
file = 'file.txt'
  
# File location
location = "/home/User/Documents"
  
# Path
path = os.path.join(location, file)
  
# Remove the file
# 'file.txt'
os.remove(path)
print("%s has been removed successfully" %file)


Output:

file.txt has been removed successfully
Code #2: If the specified path is a directory




# Python program to explain os.remove() method 
    
# importing os module 
import os
  
# Path
path = "/home/User/Documents/ihritik"
  
# Remove the specified
# file path
os.remove(path)
print("% s has been removed successfully" % file)
  
# if the specified path 
# is a directory then 
# 'IsADirectoryError' error
# will raised 
  
# Similarly if the specified
# file path does not exists or  
# is invalid then corresponding
# OSError will be raised


Output:

Traceback (most recent call last):
  File "osremove.py", line 11, in 
    os.remove(path)
IsADirectoryError: [Errno 21] Is a directory: '/home/User/Documents/ihritik'
Code #3: Handling error while using os.remove() method




# Python program to explain os.remove() method 
    
# importing os module 
import os
  
# path
path = '/home/User/Documents/ihritik'
  
# Remove the specified 
# file path
try:
    os.remove(path)
    print("% s removed successfully" % path)
except OSError as error:
    print(error)
    print("File path can not be removed")


Output:

[Errno 21] Is a directory: '/home/User/Documents/ihritik'
File path can not be removed

Reference: https://docs.python.org/3/library/os.html



Previous Article
Next Article

Similar Reads

Python groupby method to remove all consecutive duplicates
Given a string S, remove all the consecutive duplicates. Examples: Input : aaaaabbbbbb Output : ab Input : geeksforgeeks Output : geksforgeks Input : aabccba Output : abcba We have existing solution for this problem please refer Remove all consecutive duplicates from the string link. We can solve this problem in python quickly using itertools.group
2 min read
Python Set - remove() method
Python remove() Function is a built-in method to remove elements from the set. remove() method takes exactly one argument. Syntax set.remove(element) If the element passed to the remove() is present in the set then the element will be removed from the set. If the element passed to the remove() is not present in the set then KeyError Exception will
1 min read
Python List remove() Method
Python list remove() method removes a given element from the list. Example: C/C++ Code lis.remove("b") print(lis) Output['a', 'c'] List remove() Syntaxlist_name.remove(obj) Parameterobj: object to be removed from the list ReturnsThe method does not return any value but removes the given object from the list. ExceptionIf the element doesn'
5 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Python Remove Duplicates from a List
The job is simple. We need to take a list, with duplicate elements in it and generate another list that only contains the element without the duplicates in them. Examples: Input : [2, 4, 10, 20, 5, 2, 20, 4] Output : [2, 4, 10, 20, 5] Input : [28, 42, 28, 16, 90, 42, 42, 28] Output : [28, 42, 16, 90] We can use not in on list to find out the duplic
3 min read
Python | Remove empty tuples from a list
In this article, we will see how can we remove an empty tuple from a given list of tuples. We will find various ways, in which we can perform this task of removing tuples using various methods and ways in Python. Examples: Input : tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('',''),()]Output : [('ram', '15',
8 min read
Python | Remove all duplicates words from a given sentence
Given a sentence containing n words/strings. Remove all duplicates words/strings which are similar to each others. Examples: Input : Geeks for Geeks Output : Geeks for Input : Python is great and Java is also great Output : is also Java Python and great We can solve this problem quickly using python Counter() method. Approach is very simple. 1) Spl
7 min read
Python | Remove and print every third from list until it becomes empty
Given a list of numbers, Your task is to remove and print every third number from a list of numbers until the list becomes empty. Examples: Input : [10, 20, 30, 40, 50, 60, 70, 80, 90] Output : 30 60 90 40 80 50 20 70 10 Explanation: The first third element encountered is 30, after 30 we start the count from 40 for the next third element which is 6
4 min read
How to Remove Letters From a String in Python
Strings are data types used to represent text/characters. In this article, we present different methods for the problem of removing the ith character from a string and talk about possible solutions that can be employed in achieving them using Python. Input: 'Geeks123For123Geeks'Output: GeeksForGeeksExplanation: In This, we have removed the '123' ch
6 min read
Ways to remove particular List element in Python
List is an important container and is used almost in every code of day-day programming as well as web development. The more it is used, more is the required to master it and hence knowledge of its operations is necessary. Let's see the different ways of removing particular list elements. Method #1 : Using remove() remove() can perform the task of r
6 min read
Practice Tags :
three90RightbarBannerImg