Computer Science

Write a function that reads a csv file and creates another csv file with the same content except the lines beginning with 'check'.

Python File Handling

5 Likes

Answer

Let "input.csv" file contain the following data:

check1,10,A
check2,20,B
data1,30,C
check3,40,D
data2,50,E
import csv

def filter(input_file, output_file):
    with open(input_file, 'r', newline='') as f_in, open(output_file, 'w', newline='') as f_out:
        reader = csv.reader(f_in)
        writer = csv.writer(f_out)
        
        for row in reader:
            if not row[0].startswith('check'):
                writer.writerow(row)

filter('input.csv', 'output.csv')

Contents of "output.csv":

data1,30,C
data2,50,E

Answered By

2 Likes


Related Questions