【问题标题】:Read csv file into list of lists without string convertion in Python [duplicate]将csv文件读入列表列表,无需在Python中进行字符串转换[重复]
【发布时间】:2017-04-03 07:06:05
【问题描述】:

我有一个 car.csv,它有这样的行:

vhigh,vhigh,2,2,small,low,unacc

我想得到:

[vhigh,vhigh,2,2,small,low,unacc].

但是有了这段代码

import csv
a = []
with open("car.csv", 'r') as f:
    reader = csv.reader(f)
    for line in f:
        a.append([line]);

我明白了

['vhigh,vhigh,2,2,small,med,unacc\n'].

有人可以帮我吗?

【问题讨论】:

  • 我不知道 [vhigh,vhigh,2,2,small,low,unacc] 与 ['vhigh','vhigh','2','2', '小','低','unacc']

标签: python string list file csv


【解决方案1】:

当你创建阅读器时,迭代它而不是文件,这样做:

for line in reader:
    a.append(line)

或者如果你只是想要所有的行作为一个列表

a = list(reader)

把这些放在一起:

with open("car.csv", "r") as f:
    reader = csv.reader(f)
    a = list(reader)

【讨论】:

    【解决方案2】:

    拆分行内容

    line.split(',')
    

    【讨论】:

    • 如果 CSV 中的某个字段包含逗号怎么办?
    猜你喜欢
    • 2017-11-07
    • 2016-08-10
    • 1970-01-01
    • 2020-05-12
    • 2015-09-07
    • 2020-01-03
    • 2020-04-22
    • 2017-10-21
    • 2014-04-09
    相关资源
    最近更新 更多