Listing Executable Files in a Directory - Python Programming Exercise

In this exercise, you will develop a Python program that lists all executable files in a specified directory. This exercise is perfect for practicing file handling, directory traversal, and error handling in Python. By implementing this program, you will gain hands-on experience in handling file operations, directory traversal, and error handling in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Using Extra Libraries

 Exercise

Listing Executable Files In A Directory

 Objective

Develop a Python program that lists all executable files in a specified directory. The program should scan the directory for files with executable permissions (e.g., .exe, .sh, .bat, or others depending on the operating system) and display their names. Implement error handling to manage cases where the directory is invalid or inaccessible.

 Example Python Exercise

 Copy Python Code
import os
import stat

def is_executable(file_path):
    """Check if a file is executable."""
    try:
        # Check if the file has executable permissions
        return os.access(file_path, os.X_OK)
    except Exception as e:
        print(f"Error checking permissions for {file_path}: {e}")
        return False

def list_executable_files(directory):
    """List all executable files in a given directory."""
    try:
        # Check if the directory exists
        if not os.path.isdir(directory):
            print(f"Error: The directory '{directory}' does not exist or is not accessible.")
            return
        
        # List all files in the directory
        all_items = os.listdir(directory)
        executable_files = []

        # Define common executable file extensions based on OS
        executable_extensions = {
            '.exe', '.bat', '.cmd', '.sh', '.bin', '.app'
        }

        # Scan through all files in the directory
        for item in all_items:
            item_path = os.path.join(directory, item)

            # Check if it's a file and if it's executable
            if os.path.isfile(item_path) and is_executable(item_path):
                # For Unix-based systems, check the file extension too
                if any(item.endswith(ext) for ext in executable_extensions):
                    executable_files.append(item)

        # Display the executable files found
        if executable_files:
            print(f"\nExecutable files in '{directory}':")
            for file in executable_files:
                print(file)
        else:
            print(f"\nNo executable files found in '{directory}'.")

    except PermissionError:
        print(f"Error: Permission denied to access '{directory}'.")
    except Exception as e:
        print(f"Error: {e}")

def main():
    """Main function to interact with the user."""
    # Get user input for the directory
    directory = input("Enter the directory path: ")

    # List the executable files in the directory
    list_executable_files(directory)

# Run the program
if __name__ == "__main__":
    main()

 Output

Enter the directory path: /path/to/directory

Executable files in '/path/to/directory':
script.sh
program.exe
run.bat

 Share this Python Exercise

 More Python Programming Exercises of Using Extra Libraries

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Continuous Date and Time

    In this exercise, you will develop a Python program that continuously displays the current date and time in real-time. This exercise is perfect for practicing ...

  •  Sitemap Generator

    In this exercise, you will develop a Python program that generates a sitemap for a website. This exercise is perfect for practicing web crawling, URL retrieval...

  •  Generating a List of Images as HTML

    In this exercise, you will develop a Python program that generates an HTML file displaying a list of images from a specified directory. This exercise is perfec...

  •  Retrieving System Information

    In this exercise, you will develop a Python program that retrieves and displays system information, such as the operating system, CPU details, memory usage, and disk ...

  •  Sitemap Generator V2

    In this exercise, you will develop an enhanced version of a sitemap generator in Python (Sitemap Generator V2). This exercise is perfect for practicing web cra...

  •  Exploring a Directory

    In this exercise, you will develop a Python program that explores a specified directory and lists all of its contents, including files and subdirectories. This exe...