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.
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