Finding the largest file in a directory using Python
Last Updated :
29 Dec, 2020
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
print ( "Enter folder path" )
path = os.path.abspath( input ())
size = 0
max_size = 0
max_file = ""
for folder, subfolders, files in os.walk(path):
for file in files:
size = os.stat(os.path.join( folder, file )).st_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' )
|
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
Please Login to comment...