Create A Simple Python Application Save As W5 Firstname L
create A Simple Python Application Save As W5 Firstname L
Instructions create A Simple Python Application Save As W5 Firstname L Instructions create A Simple Python Application Save As W5 Firstname L Instructions create a simple Python application (Save as w5_firstname_lastname.py) . Create a Python script that takes two parameters to do the following:- 1) List all files names, size, date created in the given folder 2) Parameter1 = Root Folder name Parameter2= File size >>> to filter file size ( you can do =, > or
Paper For Above instruction
create A Simple Python Application Save As W5 Firstname L
The objective of this assignment is to develop a Python script that efficiently lists all files within a specified directory, including their names, sizes, and creation dates, with the added functionality of filtering files based on their size relative to a user-defined parameter. The script should also be capable of recursively traversing subdirectories to identify files that meet the size criteria. Additionally, robust error handling and clear documentation are required to ensure the script's reliability and usability.
Introduction
Python's powerful standard libraries facilitate directory traversal, file attribute retrieval, and command-line argument parsing. For this task, the script will utilize the os, os.path, and sys modules to implement the necessary functionality. Proper validation, exception handling, and optional output redirection are important aspects of the implementation.
Implementing the File Listing and Filtering Script
1. Parsing Command-Line Arguments
The script accepts two command-line arguments: the root folder path and the size filter condition. The first argument specifies the directory to search, while the second defines the size filter, which can involve operators like '=' , '>', '
2. Validating Inputs
Input validation ensures the provided folder exists and the size parameter conforms to acceptable formats. If validation fails, the script catches exceptions and displays generic error messages.
3. Directory Traversal and File Listing
Using os.walk(), the script traverses through the specified directory and all its subdirectories. For each file, it retrieves the name, size, and creation date, appending this information to a list.
4. Filtering Files Based on Size
The script applies the size filter to each file, considering operators and ranges. Files satisfying the condition are displayed, with the complete list optionally saved to a results file via command-line redirection.
5. Exception Handling
Wrap critical operations in try-except blocks, ensuring that errors do not reveal sensitive code details, instead providing user-friendly messages.
Sample Code Implementation
import os
import sys
import datetime
def parse_size_filter(size_str):
Parse size filter string into operator and size/range
size_str = size_str.strip()
if '-' in size_str:
parts = size_str.split('-')
if len(parts) != 2:
raise ValueError("Invalid range format.")
min_size = int(parts[0])
max_size = int(parts[1])
return ('range', min_size, max_size)
elif size_str.startswith('>='):
return ('>=', int(size_str[2:]))
elif size_str.startswith('
return ('
elif size_str.startswith('>'):
return ('>', int(size_str[1:]))
elif size_str.startswith('
return ('
elif size_str.startswith('='):
return ('=', int(size_str[1:]))
else:
Default to '=' operator
return ('=', int(size_str))
def validate_folder(path):
if not os.path.exists(path) or not os.path.isdir(path):
raise FileNotFoundError("The specified folder does not exist.")
def matches_size(file_size, operator, value):
if operator == '=':
return file_size == value
elif operator == '>':
return file_size > value
elif operator == '
return file_size
elif operator == '>=':
return file_size >= value
elif operator == '
return file_size
elif operator == 'range':
min_size, max_size = value[1], value[2]
return min_size
else:
return False
def main():
try:
if len(sys.argv) != 3:
print("Usage: python w5_firstname_lastname.py
") print("Example size filter: '>1000', '1000-5000', '=2000'")
return
folder_path = sys.argv[1]
size_filter = sys.argv[2]
validate_folder(folder_path)
filter_type, filter_value = parse_size_filter(size_filter)
files_found = []
for root, dirs, files in os.walk(folder_path):
for filename in files:
try:
filepath = os.path.join(root, filename)
stat = os.stat(filepath)
size = stat.st_size
created_time = datetime.datetime.fromtimestamp(stat.st_ctime)
if matches_size(size, filter_type, filter_value):
files_found.append({
'name': filename,
'size': size,
'created': created_time.strftime('%Y-%m-%d %H:%M:%S')
})
except Exception:
Error accessing file attributes, skip file
continue
Print results
print(f"{'File Name':
for file in files_found:
print(f"{file['name']:
except Exception as e:
Generic error message, suppress sensitive info
print("An error occurred during processing. Please check inputs and try again.")
if __name__ == "__main__":
main()
Usage Instructions
Save the script as w5_firstname_lastname.py. Run from the command line as follows:
python w5_firstname_lastname.py
For example, to list all files in "/home/user/documents" larger than 1000 bytes:
python w5_firstname_lastname.py /home/user/documents ">1000"
To filter files within size range 500 to 2000 bytes:
python w5_firstname_lastname.py /home/user/documents "500-2000"
Note: The script does not create or write to "Results.txt" directly; output redirection can be used if needed:
python w5_firstname_lastname.py /home/user/documents ">1000" > Results.txt
Conclusion
This Python script provides a robust solution for listing and filtering files based on size within a directory and its subdirectories. The implementation emphasizes input validation, exception handling, and flexibility in size filter options. It can be extended with additional features such as filtering by creation or modification dates, or exporting detailed reports.
References
- Python Software Foundation. (2023). os — Miscellaneous operating system interfaces. https://docs.python.org/3/library/os.html
- Python Software Foundation. (2023). os.path — Common pathname manipulations. https://docs.python.org/3/library/os.path.html
- Python Software Foundation. (2023). sys — Access system-specific parameters and functions. https://docs.python.org/3/library/sys.html
- Rouse, M. (2020). Working with files and directories in Python. TechTarget. https://searchstorage.techtarget.com/definition/file-and-folder
- McKinney, W. (2018). Python for Data Analysis. O'Reilly Media.
- Beazley, D., & Jones, B. (2013). Python Cookbook. O'Reilly Media.
- VanderPlas, J. (2016). Python Data Science Handbook. O'Reilly Media.
- Van Rossum, G., & Drake, F. L. (2009). Python 3 Reference Manual. Python Software Foundation.
- Frost, M. (2021). Error handling in Python. Real Python. https://realpython.com/python-exceptions/
- Harald, M. (2022). Command-line argument parsing in Python. GeeksforGeeks. https://www.geeksforgeeks.org/command-line-arguments-in-python/