I want to process a CSV file in Python and read the result in plain text as follows1AppleOrange2PenBookBed3DeskNow I want to process the CSV file as followsThe blank rows in column 1 are filled with t
You can use the csv module in Python to read and write CSV files. Here's the complete Python code that will process the CSV file as specified:
import csv
def process_csv(input_file, output_file):
# Read the CSV file
with open(input_file, 'r') as file:
reader = csv.reader(file)
rows = list(reader)
# Process the rows
for i in range(1, len(rows)):
if not rows[i][0]:
rows[i][0] = rows[i-1][0]
# Write the result to a new CSV file
with open(output_file, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(rows)
# Example usage
process_csv('input.csv', 'output.csv')
In this code, the process_csv function takes the input CSV file path and the output CSV file path as arguments. It reads the input file using csv.reader, processes the rows to fill the blanks in column 1, and then writes the result to the output file using csv.writer.
You can change the input CSV file path ('input.csv') and the output CSV file path ('output.csv') in the example usage to the paths of your own files
原文地址: https://www.cveoy.top/t/topic/ieir 著作权归作者所有。请勿转载和采集!