#Snippets #Python #README April 18, 2024

Python: List All Folder Names

About

This script will list the names of all folders found within a folder and output it to folder-names.txt

Raw Script

list-all-folder-names.py import os

def list_folder_names(directory):
    folders = [folder for folder in os.listdir(directory) if os.path.isdir(os.path.join(directory, folder))]
    return folders

def save_to_text_file(folder_names, output_file):
    with open(output_file, 'w') as file:
        for folder_name in folder_names:
            file.write(folder_name + '\n')

# Get the current directory path
directory_path = os.path.dirname(os.path.abspath(__file__))

# Specify the output file name
output_file_name = 'folder-names.txt'

# Get the list of folder names
folders = list_folder_names(directory_path)

# Save the folder names to a text file
save_to_text_file(folders, output_file_name)

print('Folder names have been saved to', output_file_name)

SEARCH