Open In App
Related Articles

Finding the largest file in a directory using Python

Like Article
Save Article
Report issue
In this article, we will find the file having the largest size in a given directory using Python. We will check all files in the main directory and each of its subdirectories. Modules required: os: The os module in Python provides a way of using operating system dependent functionality. OS module is available with Python’s Standard Library and does not require installation. Explanation:
  • The folder path is taken as input. We then walk through the entire directory using os.walk() function.
  • os.walk() returns a tuple containing the root folder name, a list of subdirectories and a list of files.
  • os.stat() is used to get the status of the file and st_size attribute returns its size in bytes.
Below is the implementation.
import os
# folder path input
print("Enter folder path")
path = os.path.abspath(input())
# for storing size of each 
# file
size = 0
# for storing the size of 
# the largest file
max_size = 0
# for storing the path to the 
# largest file
max_file =""
# walking through the entire folder,
# including subdirectories
for folder, subfolders, files in os.walk(path):
    # checking the size of each file
    for file in files:
        size = os.stat(os.path.join( folder, file  )).st_size
        # updating maximum size
        if size>max_size:
            max_size = size
            max_file = os.path.join( folder, file  )
print("The largest file is: "+max_file)
print('Size: '+str(max_size)+' bytes')

Input: Enter folder path /Users/tithighosh/Downloads/wordpress Output: The largest file is: /Users/tithighosh/Downloads/wordpress/wp-includes/js/dist/components.js Size: 1792316 bytes Input: Enter folder path /Users/tithighosh/Desktop Output: The largest file is: /Users/tithighosh/Desktop/new/graph theory.pdf Size: 64061656 bytes

Last Updated : 29 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Similar Reads