CSV文件到Python中的列表

时间:2016-07-10 21:40:18

标签: python python-3.x csv

我有一个csv文件(名为“test.csv”),其中包含带有元组的列表:

[('calculation', 1468171987.4406562, None), ('calculation', 1468171988.5840397, None), ('calculation', 1468171989.8159678, 1.9041595458984375)]5)]

如何导入此csv文件并将其内容保存到以下列表中:

record = []
导入后

record = [('calculation', 1468171987.4406562, None), ('calculation', 1468171988.5840397, None), ('calculation', 1468171989.8159678, 1.9041595458984375)]

这就是我的尝试:

import csv
    with open ("test.csv", 'rb') as f:
        reader = csv.reader(f)
        record = reader

尝试2:

import csv

with open ("test.csv", 'rb') as f:
    reader = csv.reader(f)
    record = list(reader)

然后我收到此错误:

_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

2 个答案:

答案 0 :(得分:0)

现在您已经拥有了一个CSV阅读器(我假设您的实际代码正确缩进并且运行时没有语法错误),您需要使用它来输入文件中的行。最简单的方法是:

record = list(reader)

答案 1 :(得分:0)

您可以使用ast.literal_eval

import ast
with open ("test.csv", 'r') as f:
    for line in f:
        list = ast.literal_eval(line)
        print list