Fundamentals 4 min read

Automate Folder File Listings to Excel with Python and pandas

This article walks through a Python script that reads all filenames in a folder, creates a pandas DataFrame, and saves the list as a timestamped Excel file, illustrating a simple automation workflow and offering code snippets and tips for effective data handling.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Automate Folder File Listings to Excel with Python and pandas

Introduction

The author shares a Python automation task that extracts file names from a directory and exports them to an Excel workbook using pandas.

Implementation

The following script demonstrates the process:

import os
import datetime
import pandas as pd

# Folder path
folder_path = r"<your_folder_path>"

# Get list of file names in the folder
file_names = os.listdir(folder_path)
print(file_names)

# Create a DataFrame containing the file names
df = pd.DataFrame(file_names, columns=["File Name"])

# Save as an Excel file
os.chdir(r"<your_save_path>")
route = os.getcwd()
print(route)

nowTime = datetime.datetime.now()
Update_Time = nowTime.strftime('%Y-%m-%d-%H-%M-%S')
title = "DATA-" + Update_Time + ".xlsx"
print(title)

# Write data to the Excel file
writer = pd.ExcelWriter(title)
df.to_excel(writer, encoding="utf_8_sig", sheet_name="DATA_Total", index=False)
writer.save()

The code, originally generated by ChatGPT, efficiently solves the problem. An additional refinement was later suggested to improve the workflow.

Conclusion

The article demonstrates a practical Python automation solution for handling file listings, highlighting pandas' convenience for data conversion without the need for complex styling offered by libraries like openpyxl.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

pandas
Python Crawling & Data Mining
Written by

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!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.