Python os.remove() Method
os.remove() Overview
The os.remove() method is used to remove a file from the specified path. If the specified path is a directory, OSError will be thrown.
Valid in Unix, Windows.
os.remove() Syntax
The syntax format of the remove() method is as follows.
os.remove(path)
os.remove() Parameters
- path – the path to the file to be removed
os.remove() Return Value
This method has no return value.
os.remove() Example#1
The following example demonstrates the use of the remove() method.
#!/usr/bin/python3
import os, sys
# List Directory
print ("The directory is (by os.listdir): %s" %os.listdir(os.getcwd()))
# Remove
os.remove("apidemos.com.txt")
# List the directory after removal
print ("After removal (by os.listdir): %s" %os.listdir(os.getcwd()))
Output:
os.remove() Example#2
If the specified path is a directory.
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.
import os
# Path
path = "/root/aaa"
# Remove the specified file path
os.remove(path)
print("% s has been removed successfully" % path)
Output: