Python CSV Processing: Filling Empty Cells with Previous Row Values
Sure! Here's a complete Python code that can handle CSV files with different contents as described:
import csv
def process_csv(filename):
# Read the CSV file
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter='|')
rows = list(reader)
# Process the rows
for i in range(len(rows)):
if rows[i][0] == '':
rows[i][0] = rows[i-1][0]
# Write the processed data back to the CSV file
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter='|')
writer.writerows(rows)
# Usage example
process_csv('data.csv')
This code reads the CSV file using the csv.reader function and converts it into a list of rows. Then, it loops through each row and checks if the value in the first column is empty. If it is, it fills it with the value from the previous row. Finally, it writes the processed data back to the CSV file using the csv.writer function.
You can replace 'data.csv' with the path to your actual CSV file. Make sure the file is in the same directory as the Python script or provide the full file path.
Note that this code assumes that the CSV file has a header row. If your file doesn't have a header, you can remove the header row after reading the file and add it back before writing the processed data.
原文地址: https://www.cveoy.top/t/topic/pWDa 著作权归作者所有。请勿转载和采集!