One‑Line Python Fix to Batch Add Headers to Excel Files in Subfolders
This article demonstrates how to use a short Python script with pandas and os modules to automatically locate all .xls and .xlsx files in nested subfolders, add standardized column headers, and save the updated workbooks in a single, streamlined step.
1. Introduction
In the previous post we raised a question about handling Excel files with different extensions (.xls and .xlsx) located in various subfolders, and we needed a one‑step solution.
2. Implementation
The solution, based on a suggestion from ChatGPT, requires only a minor change to the code. The full script is shown below:
import os
import pandas as pd
# Define the root folder path
folder_path = r"C:\Users\pdcfi\Desktop\新建文件夹"
# Get all subfolder paths
subfolders = [f.path for f in os.scandir(folder_path) if f.is_dir()]
# Add headers to each Excel file and save
for subfolder in subfolders:
# Get paths of all Excel files in the subfolder
excel_paths = [f.path for f in os.scandir(subfolder) if f.is_file() and (f.name.endswith(".xlsx") or f.name.endswith(".xls"))]
for excel_path in excel_paths:
# Read the Excel file
df = pd.read_excel(excel_path, header=None)
# Add column headers
df.columns = ['经度', '纬度']
# Save the Excel file
df.to_excel(excel_path, index=False)The script first defines the target directory, then uses os.scandir() to retrieve all subfolders. For each subfolder it collects the paths of .xls and .xlsx files, reads them with pandas.read_excel(), assigns the column names 经度 and 纬度 , and finally writes the modified workbook back using to_excel().
3. Summary
This concise Python program automatically adds the required headers to every Excel workbook in the specified folder hierarchy, providing a quick, one‑step resolution to the original problem. Future posts will explore handling deeper nested subfolders.
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.
