Finding the largest file in a directory using Python

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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')

chevron_right


Output:



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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.