Python create a table into variable from a csv fil

2019-03-05 06:45发布

问题:

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