Python os.remove() Method



Python method remove() of OS module accepts a path to the file we want to delete. This path can be an absolute or relative path and can be provided as a string or bytes object.

If the specified path is a directory, OSError will be raised.

Syntax

Following is the syntax for Python os.remove() method −

os.remove(path, *, dir_fd)

Parameters

The Python os.remove() method accepts two parameters namely −

  • path − This is the path, which is to be removed.

  • dir_fd − This parameter allows us to provide a file descriptor referring to a directory.

Return Value

The Python os.remove() method does not return any value.

Example

The following example shows the usage of remove() method. Here, we are removing a file named "aa.txt" from the current working directory.

import os, sys

# listing directories
print ("The dir is: %s" %os.listdir(os.getcwd()))

# removing
os.remove("aa.txt")

# listing directories after removing path
print ("The dir after removal of path : %s" %os.listdir(os.getcwd()))

When we run above program, it produces following result −

The dir is:
[ 'a1.txt','aa.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
The dir after removal of path : 
[ 'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
python_files_io.htm
Advertisements