如何在CSV文件开头添加文件名列并填充文件名?
How to Add a "Filename" Column at the Start of CSV Files (with Proper Header & Filename Only)
Looks like you're almost there! The two small issues with your current code are:
- It's inserting the full file path instead of just the filename
- It's not setting a custom header ("Filename") for the new column, but instead inserting the path into the header row too
Let's fix both problems with a few tweaks to your code. We'll use os.path utilities to get just the filename without the path or extension, and handle the header row separately.
Here's the revised code:
import csv import glob import os with open(r'C:\Python\sys_status\output.csv', 'w', newline='') as file_output: csv_output = csv.writer(file_output) for fname in glob.glob(r'C:\Python\sys_status\input.csv'): # Extract just the filename without path and .csv extension file_name_only = os.path.splitext(os.path.basename(fname))[0] with open(fname, newline='') as f_input: csv_input = csv.reader(f_input) # Handle the header row first header_row = next(csv_input) header_row.insert(0, 'Filename') csv_output.writerow(header_row) # Process and write all data rows for row in csv_input: row.insert(0, file_name_only) csv_output.writerow(row)
Key changes explained:
os.path.basename(fname)takes the full file path and returns just the filename with extension (e.g.,input.csv)os.path.splitext(...)splits that string into the name and extension, so[0]gives us the clean filename without.csv- We use
next(csv_input)to grab the header row separately, insert our custom "Filename" header, then write it to the output - For every data row after the header, we insert the cleaned filename instead of the full path
Resulting output:
When you run this code, you'll get exactly the output you wanted:
Filename,Date,Day,Server input,2018-5-20,Su,ASA input,2018-5-21,Su,ASA
内容的提问来源于stack exchange,提问作者Bunion
相关产品推荐
相关产品推荐

