How to List Folder Names and Export to Excel with Python’s os and openpyxl
This article walks through a Python automation example that uses the os module to collect subfolder names from a specified directory and the openpyxl library to write those names into an Excel workbook, providing full code and explanations.
Introduction
Hello, I'm Pipi. This article discusses a Python automation task that was raised in a group chat, focusing on extracting folder names and saving them to an Excel file.
Implementation Process
A contributor provided a reference article that needed slight modifications, and another contributor shared the final solution.
The following code uses the os module to walk a directory and the openpyxl library to write the folder names into an Excel workbook.
# Example code
import os
from openpyxl import Workbook
# Set the target directory
dir_path = r'C:\Users\Desktop\已完成'
# Get all subfolder names
sub_dirs = [x[0] for x in os.walk(dir_path)]
# Store folder names in Excel
wb = Workbook()
ws = wb.active
for i in range(1, len(sub_dirs)):
ws.cell(row=i, column=1, value=sub_dirs[i])
# Save the Excel file
wb.save('sub_dirs_names.xlsx')This script walks through the specified directory, collects each subfolder name, writes them into the first column of a new Excel file, and saves the workbook.
Conclusion
The article presented a practical Python solution for automating file‑system tasks and exporting results to Excel, providing both explanation and ready‑to‑run code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
