Here is a Python solution to get a list of all files and directories under a specified path. This example uses the os module, which is part of the Python Standard Library, making it readily available for use without needing to install additional packages.
Using os Module
python
import os
def get_files_and_directories(path):
"""
Returns two lists: one for files and one for directories under the given path.
:param path: The path to the directory you want to scan.
:return: A tuple of two lists. The first list contains file names, and the second contains directory names.
"""
try:
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
directories = [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
return files, directories
except FileNotFoundError:
print(f"The path '{path}' does not exist.")
return [], []
except PermissionError:
print(f"No permission to access the path '{path}'.")
return [], []
except Exception as e:
print(f"An error occurred: {e}")
return [], []
def get_files_and_directories_recursively(path):
"""
Recursively returns all files and directories under the given path.
:param path: The path to the directory you want to scan.
:return: A tuple of two lists. The first list contains file paths, and the second contains directory paths.
"""
try:
all_files = []
all_directories = []
for root, dirs, files in os.walk(path):
all_files.extend([os.path.join(root, file) for file in files])
all_directories.extend([os.path.join(root, dir) for dir in dirs])
return all_files, all_directories
except FileNotFoundError:
print(f"The path '{path}' does not exist.")
return [], []
except PermissionError:
print(f"No permission to access the path '{path}'.")
return [], []
except Exception as e:
print(f"An error occurred: {e}")
return [], []
# Example usage
if __name__ == "__main__":
path_to_scan = '/your/target/path' # Update this with your desired path
# Non-recursive example
files, directories = get_files_and_directories(path_to_scan)
print("Files:")
for file in files:
print(file)
print("\nDirectories:")
for directory in directories:
print(directory)
# Recursive example
all_files, all_directories = get_files_and_directories_recursively(path_to_scan)
print("\n\nAll Files (Recursive):")
for file in all_files:
print(file)
print("\nAll Directories (Recursive):")
for directory in all_directories:
print(directory)
Using pathlib Module (Python 3.4+)
For a more modern Pythonic approach, you can use the pathlib module, which offers a more elegant way of handling filesystem paths.
python
from pathlib import Path
def get_files_and_directories(path):
"""
Returns two lists: one for files and one for directories under the given path.
:param path: The path to the directory you want to scan.
:return: A tuple of two lists. The first list contains file names, and the second contains directory names.
"""
try:
p = Path(path)
files = [f.name for f in p.iterdir() if f.is_file()]
directories = [d.name for d in p.iterdir() if d.is_dir()]
return files, directories
except FileNotFoundError:
print(f"The path '{path}' does not exist.")
return [], []
except PermissionError:
print(f"No permission to access the path '{path}'.")
return [], []
except Exception as e:
print(f"An error occurred: {e}")
return [], []
def get_files_and_directories_recursively(path):
"""
Recursively returns all files and directories under the given path.
:param path: The path to the directory you want to scan.
:return: A tuple of two lists. The first list contains file paths, and the second contains directory paths.
"""
try:
p = Path(path)
all_files = [f for f in p.rglob('*') if f.is_file()]
all_directories = [d for d in p.rglob('*') if d.is_dir()]
return all_files, all_directories
except FileNotFoundError:
print(f"The path '{path}' does not exist.")
return [], []
except PermissionError:
print(f"No permission to access the path '{path}'.")
return [], []
except Exception as e:
print(f"An error occurred: {e}")
return [], []
# Example usage
if __name__ == "__main__":
path_to_scan = Path('/your/target/path') # Update this with your desired path
# Non-recursive example
files, directories = get_files_and_directories(path_to_scan)
print("Files:")
for file in files:
print(file)
print("\nDirectories:")
for directory in directories:
print(directory)
# Recursive example
all_files, all_directories = get_files_and_directories_recursively(path_to_scan)
print("\n\nAll Files (Recursive):")
for file in all_files:
print(file)
print("\nAll Directories (Recursive):")
for directory in all_directories:
print(directory)
Notes:
Path Input: Make sure to replace '/your/target/path' with the actual path you want to scan.
Permissions: Running these scripts requires read permission on the target directory and its contents.
Recursive Listing: If you need a recursive listing (i.e., listing all files and directories under all subdirectories), you can use the os.walk() function or pathlib.Path.rglob(). Examples of both are provided above.