简体   繁体   English

CSV文件到Python列表中

[英]CSV file to a list in Python

I have a csv file (named "test.csv") containing this list with tuples: 我有一个包含此列表和元组的csv文件(名为“ test.csv”):

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

How can I import this csv file and save its contents to a list like this: 如何导入此csv文件并将其内容保存到这样的列表中:

record = []

after the import 导入后

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

This is what I tried: 这是我尝试的:

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

Attempt 2: 尝试2:

import csv

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

Then I get this error: 然后我得到这个错误:

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

Now that you have a CSV reader (I assume your real code is indented correctly and runs without syntax error), you need to use it to input the lines from the file. 现在您已经有了CSV阅读器(我假设您的真实代码已正确缩进并且可以在运行时没有语法错误),您需要使用它来输入文件中的行。 The simplest way is like this: 最简单的方法是这样的:

record = list(reader)

You can use ast.literal_eval 您可以使用ast.literal_eval

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM