Python create a table into variable from a csv file

北慕城南 提交于 2019-12-02 09:37:09

I would recommend using the dictreader from the csv module. You can pass a delimiter argument, which would be , in this case. The first line will be used as keys for the dict.
See: http://docs.python.org/2/library/csv.html

Example:

import csv
data = []
with open('example.csv',  'r') as f:
    reader = csv.DictReader(f, delimiter=',')
    for line in reader:
        line['Price'] = float(line['Price'])
        data.append(line)

now just pass along the dataobject, or put this into a function you call whenever you need it.

# Create holder for all the data, just a simple list will do the job.
data = []

# Here you do all the things you do, open the file, bla-bla...
tree_file.readline() # skip first row
for row in tree_file:
    fields = row.strip().split(",") #make Into fields
    data.append({
        'length' : float(fields[0]),
        'price'  : float(fields[1]),
        'code'   : fields[2] 
    })

# ...close the open file object and then just use the data list...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!