import os def list_directory_recursively(start_path): """ Lists all folders and their files recursively starting from the given path. Args: start_path (str): The path to the directory to start listing from. """ if not os.path.isdir(start_path): print(f"Error: '{start_path}' is not a valid directory.") return print(f"Listing contents of: {start_path}\n") # os.walk yields a 3-tuple: (dirpath, dirnames, filenames) # dirpath: The path of the current directory. # dirnames: A list of the names of the subdirectories in dirpath (not full paths). # filenames: A list of the names of the non-directory files in dirpath (not full paths). for root, dirs, files in os.walk(start_path): # Print the current directory path # Use os.path.relpath to show path relative to start_path, or keep root for full path relative_root = os.path.relpath(root, start_path) if relative_root == '.': # This is the starting directory itself print(f"Folder: {os.path.basename(root)}/") else: print(f"Folder: {relative_root}/") # Print files in the current directory if files: for file in sorted(files): # Sort files for consistent output print(f" File: {file}") # You can also print subdirectories found at this level if you wish # for dir_name in sorted(dirs): # print(f" Subfolder: {dir_name}/") print() # Add an empty line for readability between folders if __name__ == "__main__": # Example usage: # Get directory path from user directory_to_list = input("Enter the path to the Linux directory you want to list (e.g., /home/user/documents): ") list_directory_recursively(directory_to_list) # You can also hardcode a path for testing: # list_directory_recursively("/path/to/your/test_directory")