Delete files larger than a specific size in Python

If you want to remove the useless files that consume unnecessary space on your device then this tutorial of deleting files larger than a particular size in Python is for you. You can permanently delete files greater than a particular size with the help of Python programming. So, read the following text very carefully to learn and explore new methods.

OS module:

Deleting the files requires the OS module and the functions shown below.
os.walk– This function is responsible for producing the names of the files in the folder from which we want to delete the files.
os.path.join– This function is responsible for joining the path of two files into one single path name.
os.path.getsize– This function is used to get or obtain the size of a file inside a directory or a folder.
os.remove– This function is used to remove or delete one or more files according to the requirement.

Python Program: Delete files larger than a specific size

# import the required module
import os
folder_path='C:/Users/kovid/OneDrive/Documents/sample files'
for root, _, files in os.walk(folder_path):
    for f in files:
            # set the size of the files you want to delete
            if os.path.getsize(complete_path) > 1024:
                # function to delete the files
        except FileNotFound:
            print("This file does not exist"+ complete_path)

These files have been deleted forever from my device as the sizes of these files were larger than 1024 bytes. Also, notice while copying the path of the directory kindly replace the ‘\’ with ‘/’ to avoid any error.

Delete files larger than a specific size in Python

You can also delete the files which are lesser than a particular size by just interchanging this ‘>’ with ‘<‘ in the program above.

Also read: How to delete a file in Python with examples

Leave a Reply

Your email address will not be published. Required fields are marked *