-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.py
More file actions
97 lines (73 loc) · 3.54 KB
/
Copy pathscanner.py
File metadata and controls
97 lines (73 loc) · 3.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import os
from list_validator import is_list_of_special_dicts
def scan_directory(directory_path: str) -> list[dict[str, str]]:
"""
Scans the given directory (excluding subdirectories) and
returns list of dictionaries each contains
file details including name, extension, size, and path.
Args:
directory_path (str): The path of the directory to scan.
Returns:
list[dict[str, str]]: A list of dictionaries where each dictionary contains details
about a file (name, extension, size, path).
Raises:
FileNotFoundError: If the given directory path does not exist.
IsADirectoryError: If the given path is not a directory.
"""
# Check if the given directory exists.
if not os.path.exists(directory_path):
raise FileNotFoundError(f"The directory '{directory_path}' does not exist.")
# Check if the path is actually a directory.
if not os.path.isdir(directory_path):
raise IsADirectoryError(f"The path '{directory_path}' is not a directory.")
# Initialize an empty list to store details about each file in the directory.
scan_results = []
# Iterate over each item in the folder
for file in os.listdir(directory_path):
# Get the full file path by joining the folder path and file name
file_path = os.path.join(directory_path, file)
# Process only files (ignore subdirectories)
if os.path.isfile(file_path):
try:
# Attempt to get the file size in bytes
size = os.path.getsize(file_path)
except Exception as e:
# If an error occurs while getting file size, print the error and set size to 0
print(f"Error getting size for {file}: {e}")
size = 0
name, extension = os.path.splitext(file) # Extract the file name and extension.
# Append the file details as dictionary to the scan_results list
scan_results.append({
"name": name,
"extension": extension[1:].lower(), # Save it Without dot '.'
"size": size,
"path": file_path
})
# Return file details as list of dictionaries
return scan_results
def display_scan_results(scan_results: list[dict[str, str]]) -> None:
"""
Displays the results of the directory last scan: (file name, extension, size in bytes, and path).
Args:
scan_results (list[dict]): List of dictionaries containing file details to display
Returns: None
Raises:
TypeError: If 'scan_results' is not a list of dictionaries with required keys.
ValueError: If there are no files in the last scan.
"""
# Validates 'scanned_files' is a list of dictionaries with required keys.
if not is_list_of_special_dicts(scan_results):
raise TypeError("'scan_results' must be a list of dictionaries with required keys.")
# If there are no files in the last scan, raise an exception.
if not scan_results:
raise ValueError("The Directory does not contain any files to analyze.")
# Print a header for the scanned directory.
print(f"\n✅ Scan Result:")
print("=" * 60)
print(f"{'File Name': <13} {'Extension': <12} {'Size(bytes)': <13} Full Path")
print("=" * 60)
# Iterate over each file and print its details.
for file in scan_results:
print(f"{file['name']: <15} {file['extension']: <10} {file['size']: <2} {'bytes':<8} {file['path']}")
# Print a footer for the scanned directory.
print("=" * 60)