Home > OS >  Python-CSV write column(s) at given indices to new file
Python-CSV write column(s) at given indices to new file

Time:12-06

I am trying to write the column(s) in a csv file where a word is present. the example shown here is for "car".

NOTE: CANNOT USE PANDAS

here is the sample in_file:

12,life,car,good,exellent
10,gift,truck,great,great
11,time,car,great,perfect

the desired output for out_file is:

car
truck
car

This is the current code:

def project_columns(in_file, out_file, indices):
    #indices[0] = 2
    col = indices[0]
    with open(in_file) as f:
        reader = csv.reader(f)
        
        with open(out_file, 'w') as out:
            w = csv.writer(out)
            for row in reader:
                w.writerow(row[col])

the variable indices contains the indices of the column. for "car" indices = [2,2].

out_file currently contains:

c,a,r
t,r,u,c,k
c,a,r

How should I fix this to get the desired output?

CodePudding user response:

cat car.csv                                                                                                                                                                
12,life,car,good,exellent
10,gift,truck,great,great
11,time,car,great,perfect

import csv

with open('car.csv') as car_file:
    r = csv.reader(car_file)
    with open('out.csv', 'w') as out_file:
        w = csv.writer(out_file)
        for row in r:
            w.writerow([row[2]])

cat out.csv                                                                                                                                                               
car
truck
car



  • Related