DeveloperBreeze

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}")

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
bash

Finding the Top 10 Biggest Files on an Ubuntu Server

After executing the command, you'll see a list of the top 10 largest files, along with their sizes. For example:

1.2G    /var/log/largefile.log
900M    /home/user/bigdata.dat
850M    /opt/application/hugefile.bin
...

Aug 11, 2024
Read More
Code
php

File Listing with glob()

No preview available for this content.

Jan 26, 2024
Read More
Code
python

Batch File Renaming Using os Module

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!