Online Tutorials & Training Materials | STechies.com
Register Login

Python Delete File or Directory

24 Dec 2019 11:57 am || 0

In this tutorial, we are going to learn how to remove a file that are no longer needed. In Python, you can easily do this with the remove(), rmdir(), rmtree() method in the OS module.

Note: Files or directory, once removed, will get deleted permanently.

What is Python OS module

If you want to interact with the operating system through Python, you will have to do it through the OS module. This module has multiple functions to create, remove, or change the content of a directory in an OS. You can use its python functions like name(), environ(), getuid(), and uname() to communicate with operating systems like Mac, Windows, and Linux.

How to Delete File in Python?

You can use the following method to delete a file or directory in Python:

  1. os.remove() removes file only
  2. os.rmdir() removes an empty directory.
  3. shutil.rmtree() deletes a directory and all its contents.
  4. unlink() removes file only

Using os.remove() method to remove single file

Code:

# Importing the OS library
import os

# Inbuilt function to remove files
os.remove("demo.txt")
print("File removed successfully")

Output:

File removed successfully

In the above example, we are just deleting the file; if the given file does not exist, then it will generate an error.

os.remove() method will search the file to remove in the working directory

Check if File exists using os.path.isfile

To avoid error, we can check if a given file exists or not and then do the file delete operation

Code:

#importing the OS Library
import os

#checking if file exist or not
if(os.path.isfile("demo.txt")):
    
    #Inbuilt function to remove files
    os.remove("demo.txt")
    
    #Printing the confirmation message
    print("File removed successfully")
else:
print("File does not exist") 

Output:

File removed successfully

In the above example before deleting the file, we are first checking if file exists at a particular location and then deleting the file

Delete file at a specific location using os.path.join

Code:

# Python Program to remove file on the specified location

# Importing the OS library
import os

# Specify file path
path = "D:\Temp"

# File name to remove
fileName = "demo.txt"

# Creat file path
accurateLocation = os.path.join(path,fileName)

# check if file exist or not
if(os.path.isfile(accurateLocation)):
    
    # Remove files
    os.remove(accurateLocation)
    
    # Print confirmation message
    print("File removed successfully")
else:
print("File does not exist")

Output:

File removed successfully

In the above example, we are using os.path.join method to create a file path.

Error handling while deleting file using Using try-catch

Code:


# Python Program to remove the file on the specified location using try-catch

# Importing the OS library
import os

# Path of the file
path = "D:\Temp"

# File name to remove
fileName = "demo.txt"

# Creating the path
accurateLocation = os.path.join(path,fileName)

#Try Catch for handling the error better
try:
    os.remove(accurateLocation)
    print("%s has been removed successfully" %accurateLocation)
except OSError as e:
print€

Output:

FileNotFoundError: [WinError 2] The system cannot find the file specified: '"D:\Temp\demo.txt'

In the above example, we are using try, catch error handling to print an error message.

Remove directory or folder using os.rmdir module

# Python program to remove directory
# Remove only empty directory

#Importing the OS Library
import os

#Path of the parent directory
path = "D:\remove"

# Path to a directory which we want to remove
removeDirPath = "D:\remove\demo"

# Check if directory exist or not
if(os.path.isfile(removeDirPath)):
    #Try Catch for handling the error better
    try:
        # Print available directory and files in parent directory
        print('Available directory: ',os.listdir(path))
        
        # Function to remove the directory
        os.rmdir(removeDirPath)
        print("%s - Has been removed " %path)
        
        #Printing the available directory and files in parent directory after delete
        print('Available directory after deleting: ',os.listdir(path))
    except OSError as e:
            #Printing the error { if we found any error }
        print(e)
else:
print("Directory dose not exist")

Output:

Available directory: ['demo', 'demo_1', 'demo_2', 'demo_4']

D:\remove\demo - has been removed

Available directory after deleting: ['demo_1', 'demo_2', 'demo_4']

In the above example, we are using os.rmdir module to remove the directory in a specific location; this function will generate an error if the given directory is not empty.

Delete directory, subdirectory & files recursively using shutil.rmtree

Code:

# Remove directory ( If directory has sub-directories and files in it)

# Importing the OS Library
import os
# Importing the shutil Library
import shutil

# Path of the parent directory
path = "D:\remove"

# Path of the directory which we want to delete
removeDirPath = "D:\remove\demo"

# Check if folder exist or not
if(os.path.isfile(removeDirPath)):
    #Try Catch for handling the error
    try:
        # printing the list of directories in the parent directory
        print('Available directory: ',os.listdir(path))
        
        # Removing the directory
        shutil.rmtree(removeDirPath)
        
        # Print confirmation message
        print("%s - has been removed " %path)
        
        # Print directory list after delete
        print('Available directory after deleting: ', os.listdir(path))
        
    except OSError as e:
        #Printing the error { if we found any error }
        print(e)
else:
print("Directory dose not exist")

Output:

Available directory: ['demo-1', 'demo-1.txt', 'demo-2', 'demo-2.txt', 'demo-3', 'demo-3.txt']

D:\remove\demo - has been removed

Available directory after deleting: ['demo_1', 'demo_2', 'demo_4']

Deleting a file using os.unlink method

os.unlink()is a same method as os.remove()only change in name, it is a Unix name of remove() method

os.unlink()method only remove files not directories

Code:

# Remove file in the using unlink() method

# Importing the OS Library
import os

# Check if file exist or not
if(os.path.isfile("demo.txt")):
    
    # Inbuilt function to remove files
    os.unlink("demo.txt")
    #Printing the confirmation message
    print("File has been removed successfully")
else:
    #File does not exist
print("File does not exist")

Output:

File has been removed successfully

Delete all files in a directory with extension using endswith() module (wild-cards)

Code

# Removing a files according to their extension

# Importing the OS library
import os

# Path of the folder
target = "F:\Temp"

# Print list of available files in folder
print(os.listdir(target))

for x in os.listdir(target):
    #checking, Is file has .css extension
    if(x.endswith('.css')):
        print("Deleting File : ", x)
        #Function to remove the file
        os.unlink(target + x)
        print('%s has been deleted Successfully!' %x)

Output:

['sandbox1.js', 'sandbox2.js', 'sandbox3.js', 'style1.css', 'style2.css', 'style3.css']

Deleting File : style1.css

style1.css has been deleted Successfully!

Deleting File : style2.css

style2.css has been deleted Successfully!

Deleting File : style3.css

style3.css has been deleted Successfully!

Key Points

  • File or directory once removed cant be restored
  • To avoid system error, we first need to check if file or directory is available