简体   繁体   中英

Adding specific column from csv file to new csv file

I am trying to copy few columns from a csv file to a new CSV file. I have written below code to fulfill my requirements. But it is not giving me the expected output. Can someone please help me to get the required results..

import csv

f = csv.reader(open("C:/Users/...../file.csv","rb"))                
f2= csv.writer(open("C:/Users/.../test123.csv","wb"))

for row in f:

      for column in row:

          f2.writerow((column[1],column[2],column[3],column[7]))

f.close()  
f2.close()

The second iteration over each row is not necessary. Just access the columns in that row with the column index.

Also, I don't think there's a close method in csv reader and writer.

import csv

f = csv.reader(open("file.csv","rb"))
f2= csv.writer(open("test123.csv","wb"))

for row in f:
    f2.writerow((row[1],row[2],row[3],row[7]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM