Code Programming Tutorials, Guides & Best Practices
Explore 184+ expertly crafted code tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.
Adblocker Detected
It looks like you're using an adblocker. Our website relies on ads to keep running. Please consider disabling your adblocker to support us and access the content.
Code
python
List Files in a Directory Using os Module
import os
# Define the directory to list files from
directory_path = 'my_dir'
try:
# Check if the directory exists
if not os.path.exists(directory_path):
raise FileNotFoundError(f"The directory '{directory_path}' does not exist.")
# List all files and directories in the specified path
files_list = os.listdir(directory_path)
if not files_list:
print(f"The directory '{directory_path}' is empty.")
else:
print(f"Files and directories in '{directory_path}':")
for file in files_list:
print(f" - {file}")
except FileNotFoundError as e:
print(e)
except PermissionError:
print(f"Permission denied: Unable to access the directory '{directory_path}'.")
except Exception as e:
print(f"An unexpected error occurred: {e}")Jan 26, 2024
Read More