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
Show 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