简体   繁体   中英

read and save a specific column from csv file

need help! using previous topics, I found how I can read data form csv file and I do not have problem with this but I can not save a specific column (eg column 4 from file.csv) as new.csv file. my script prints column 4 correctly but it does not save it.

import csv

with open('file.csv') as csvfile:
    file1 = csv.reader(csvfile, delimiter=',')
    fourth_col = []

    for cols in file1:
        fourth_col = cols[3]
        print (fourth_col)

        new_file = open('new.csv', 'w')
        writer = csv.writer(new_file)
        writer.writerows(fourth_col)
        new_file.close()

I tried the following code and it is working fine

import csv

new_file = open('new.csv', 'w')
writer = csv.writer(new_file)

with open('file.csv') as csvfile:
    file1 = csv.reader(csvfile, delimiter=',')
    fourth_col = []

for cols in file1:
    fourth_col = cols[3]
    print(fourth_col)
    writer.writerows(fourth_col)

new_file.flush()
new_file.close()

sample files:

file.csv

a,b,c,d,e
f,g,h,i,j
k,l,m,,n
,,,o,

new.csv

d
i
o

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