Python 从 CSV 文件创建一个变量表
我想创建一个变量,里面是一个看起来像真实CSV文件的表格:
Length Price Code
10.05 0.78 AB89H
20 5 HB20K
这是我在每个函数中都要做的事情,所以也许我可以一次性做到这件事……
tree_file.readline() # skip first row
for row in tree_file:
field=row.strip()
field=field.split(",") #make Into fields
price=int(field[1])
我想要一个函数,它可以从CSV文件创建一个表格,这样我就可以在其他所有函数中使用这个表格。这样我就不需要每次在每个函数里都打开CSV文件,处理它们,把数据分成字段。
我不需要打印出实际的表格!
2 个回答
0
在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后把它存储到另一个地方。这个过程就像是把水从一个桶倒到另一个桶一样。
有些时候,我们可能会遇到一些问题,比如数据格式不对,或者存储的地方不够用。这就像是你想把水倒进一个小杯子里,但水桶里的水太多了,杯子装不下。
为了避免这些问题,我们可以提前检查一下数据,确保它们是正确的,或者在存储之前先把多余的数据处理掉。这样就能顺利地把数据从一个地方转移到另一个地方,而不会出现意外的麻烦。
总之,处理数据就像是搬家一样,需要提前规划,确保每样东西都能放到合适的位置。
# 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...
2
我建议使用csv模块中的dictreader。你可以传递一个分隔符参数,在这个例子中就是逗号(,)。第一行会被用作字典的键。
可以参考这里:http://docs.python.org/2/library/csv.html
示例:
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)
现在只需传递数据对象,或者把这个放到一个函数里,每当需要的时候调用它就可以了。