【问题标题】:read and save a specific column from csv file从 csv 文件中读取并保存特定列
【发布时间】:2019-02-28 13:19:25
【问题描述】:

需要帮助!使用以前的主题,我发现了如何从 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()

【问题讨论】:

    标签: python csv


    【解决方案1】:

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

    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
    

    【讨论】:

    • 它有效。谢谢!还有一个问题:有没有办法将 new.csv 写成新的。 txt?
    • 是的,你可以,只需更改文件名和扩展名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    相关资源
    最近更新 更多