Python – How to delete a file or folder?

In this tutorial, we are going to learn how to delete a file or directory in Python. The process of removing a file or folder in Python is straightforward using the os module.

  • os.remove – Deletes a file.
  • os.rmdir – Deletes a folder.
  • shutil.rmtree – Deletes a directory and all its contents.

1. Deletes a file.

First, we will see a method to delete a file from a directory using the os.remove


#!/usr/bin/python
import os

# getting the filename from the user
file_path = input("Enter filename:- ")

# checking whether file exists or not
if os.path.exists(file_path):
    # removing the file using the os.remove() method
    os.remove(file_path)
else:
    # file not found message
    print("File not found in the directory")

Output


 Enter filename:- sample.txt
 File not found in the directory

2. Deletes a folder.

The folder which we are going to delete must be empty. Python will shows a Warning is stating that the folder is not empty. Before removing a folder, make sure that it is empty. We can get the list of files present in the directory using os.listdir() Method. From that, we can check whether the folder is empty or not.


#!/usr/bin/python
import os

# getting the folder path from the user
folder_path = input("Enter folder path:- ")

# checking whether folder exists or not
if os.path.exists(folder_path):

    # checking whether the folder is empty or not
    if len(os.listdir(folder_path)) == 0:
        # removing the file using the os.remove() method
        os.rmdir(folder_path)
    else:
        # messaging saying folder not empty
        print("Folder is not empty")
else:
    # file not found message
    print("File not found in the directory")

Output


Enter folder path:- sample
Folder is not empty

3. Deletes a directory and all its contents.


#!/usr/bin/python
import os
import sys
import shutil

# Get directory name
mydir= input("Enter directory name: ")

try:
    shutil.rmtree(mydir)
except OSError as e:
    print("Error: %s - %s." % (e.filename, e.strerror))

Output


Enter directory name: d:\logs
Error: d:\logs - The system cannot find the path specified.

References

About the Author

author image
Hafeezul Kareem
I am a Pythoneer currently studying 3rd year in my Computer Science course. I will be a computer science graduate in 2 years. I am very fond of Python and Programming. I love to learn new technologies and enthusiastic about sharing my knowledge across the programming community.

Comments

avatar