首页 > 解决方案 > 从 csv 文件中读取并保存特定列

问题描述

需要帮忙!使用以前的主题,我发现了如何从 csv 文件中读取数据,对此我没有问题,但我无法将特定列(例如 file.csv 中的第 4 列)保存为 new.csv 文件。我的脚本正确打印了第 4 列,但没有保存它。

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()

标签: pythoncsv

解决方案


我尝试了以下代码,它工作正常

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()

示例文件:

文件.csv

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

新的.csv

d
i
o

推荐阅读