Python create a table into variable from a csv file

别说谁变了你拦得住时间么 提交于 2019-12-31 07:03:30

问题


I want to create a table into variable something that looks like actual csv file:

Length    Price     Code 
10.05      0.78     AB89H
20         5        HB20K

This is something that What I do to every function I am working with So maybe I can do it once perhaps...

    tree_file.readline() # skip first row
    for row in tree_file:
       field=row.strip()
       field=field.split(",") #make Into fields
       price=int(field[1])

I want a function that create a table from csv file so I can use this table for all my other function. So I don't have to all the time open csv file in each function and strip them and make them in field.

I don't need to print actual table!


回答1:


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.




回答2:


# 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...


来源:https://stackoverflow.com/questions/14755119/python-create-a-table-into-variable-from-a-csv-file

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