Ejercicio
Mostrar Contenidos Del Directorio
Objectivo
Desarrollar un programa Python que muestre el contenido de un directorio específico. El programa debe enumerar todos los archivos y subdirectorios dentro del directorio indicado. Incluir opciones para filtrar los resultados según el tipo o el tamaño del archivo, y gestionar errores de rutas de directorio no válidas o directorios inaccesibles.
Ejemplo de ejercicio de Python
Mostrar código Python
import os
def list_directory_contents(directory, file_type=None, min_size=None, max_size=None):
"""Display the contents of a directory with filtering options."""
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 and subdirectories
all_items = os.listdir(directory)
# Filter items based on the file type
filtered_items = []
for item in all_items:
item_path = os.path.join(directory, item)
if os.path.isfile(item_path):
# Filter by file type (extension)
if file_type and not item.endswith(file_type):
continue
# Filter by file size if specified
if min_size and os.path.getsize(item_path) < min_size:
continue
if max_size and os.path.getsize(item_path) > max_size:
continue
filtered_items.append((item, "File"))
elif os.path.isdir(item_path):
filtered_items.append((item, "Directory"))
# Display the filtered contents
if filtered_items:
print(f"\nContents of '{directory}':")
for item, item_type in filtered_items:
print(f"{item} ({item_type})")
else:
print(f"\nNo matching files or directories 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: ")
# Get optional filters for file type and file size
file_type = input("Enter file type to filter by (e.g., .txt, .jpg) or leave blank for no filter: ").strip()
if file_type == "":
file_type = None
try:
min_size = int(input("Enter minimum file size in bytes (or 0 for no minimum): ").strip())
except ValueError:
min_size = 0
try:
max_size = int(input("Enter maximum file size in bytes (or 0 for no maximum): ").strip())
except ValueError:
max_size = 0
# List the directory contents with the given filters
list_directory_contents(directory, file_type, min_size, max_size)
# Run the program
if __name__ == "__main__":
main()
Output
Enter the directory path: /path/to/directory
Enter file type to filter by (e.g., .txt, .jpg) or leave blank for no filter: .txt
Enter minimum file size in bytes (or 0 for no minimum): 1000
Enter maximum file size in bytes (or 0 for no maximum): 5000
Contents of '/path/to/directory':
file1.txt (File)
file2.txt (File)
subfolder1 (Directory)
subfolder2 (Directory)
Código de ejemplo copiado
Comparte este ejercicio de Python