Exercise
Exploring A Directory
Objective
Develop a Python program that explores a specified directory and lists all of its contents, including files and subdirectories. The program should display the names of the files and directories, as well as additional details such as file size, type, and creation date. Implement error handling for invalid directory paths and inaccessible directories.
Example Python Exercise
Show Python Code
import os
import time
def get_file_info(file_path):
"""Get details like size, type, and creation date for a given file."""
try:
file_size = os.path.getsize(file_path) # File size in bytes
file_creation_time = os.path.getctime(file_path) # File creation time (epoch)
file_type = "Directory" if os.path.isdir(file_path) else "File"
file_creation_date = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(file_creation_time))
return file_size, file_type, file_creation_date
except Exception as e:
print(f"Error retrieving information for {file_path}: {e}")
return None, None, None
def explore_directory(directory_path):
"""Explore the specified directory and list its contents."""
if not os.path.exists(directory_path):
print(f"Error: The directory '{directory_path}' does not exist.")
return
if not os.path.isdir(directory_path):
print(f"Error: '{directory_path}' is not a valid directory.")
return
print(f"Exploring directory: {directory_path}\n")
try:
# List the files and directories
for root, dirs, files in os.walk(directory_path):
# Print the details for subdirectories
for directory in dirs:
dir_path = os.path.join(root, directory)
file_size, file_type, file_creation_date = get_file_info(dir_path)
print(f"Directory: {directory}")
print(f" Path: {dir_path}")
print(f" Size: {file_size} bytes")
print(f" Type: {file_type}")
print(f" Created on: {file_creation_date}\n")
# Print the details for files
for file in files:
file_path = os.path.join(root, file)
file_size, file_type, file_creation_date = get_file_info(file_path)
print(f"File: {file}")
print(f" Path: {file_path}")
print(f" Size: {file_size} bytes")
print(f" Type: {file_type}")
print(f" Created on: {file_creation_date}\n")
except PermissionError:
print(f"Error: Permission denied while accessing '{directory_path}'")
except Exception as e:
print(f"Unexpected error: {e}")
def main():
"""Main function to initiate the directory exploration."""
directory_path = input("Enter the directory path to explore: ").strip()
explore_directory(directory_path)
if __name__ == '__main__':
main()
Output
Enter the directory path to explore: /home/user/Documents
Exploring directory: /home/user/Documents
Directory: SubFolder1
Path: /home/user/Documents/SubFolder1
Size: 4096 bytes
Type: Directory
Created on: 2024-01-15 10:35:12
File: example_file.txt
Path: /home/user/Documents/example_file.txt
Size: 2048 bytes
Type: File
Created on: 2023-12-01 14:22:45
File: image.jpg
Path: /home/user/Documents/image.jpg
Size: 102400 bytes
Type: File
Created on: 2023-11-18 08:11:30
Share this Python Exercise