Python从csv文件创建一个表到变量中 [英] Python create a table into variable from a csv file

查看:386
本文介绍了Python从csv文件创建一个表到变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 长度价格代码
我想创建一个表格到变量中,看起来像实际的csv文件: 10.05 0.78 AB89H
20 5 HB20K

这就是我对每个函数做的事I我正在工作所以也许我可以做一次,也许... ...

$ $ $ code> tree_file.readline()#跳过第一行
为tree_file中的行:
field = row.strip()
field = field.split(,)#make进入字段
price = int(field [1])$ ​​b $ b

我需要一个从csv文件创建表的函数,所以我可以使用这个表来处理所有其他函数。所以我不必一直打开每个函数中的csv文件,并将它们剥离并放在字段中。



我不需要打印实际表格!

解决方案

我会推荐使用csv模块中的dictreader。你可以传递
一个分隔符参数,在这种情况下就是这样。
第一行将用作字典的键。

请参阅:
http://docs.python.org/2/library/csv.html



示例:

 导入csv 
data = []
以open('example.csv','r')作为f :
reader = csv.DictReader(f,delimiter =',')
为阅读器中的行:
line ['Price'] = float(line ['Price'])
data.append(line)

现在只需传递数据对象,或将其放入函数你随时都可以打电话。


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!

解决方案

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.

这篇关于Python从csv文件创建一个表到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆