我正在预处理一个csv文件,并希望输出3个由字段过滤的csv文件数据组成的字典。
设置为:
import csv
from m_functions import region_goals
csvFile = # a file path
mnDict = dict()
nlDict = dict()
neDict = dict()
# READ CSV
weekList = csv.reader(open(csvFile))
# CREATE DICTIONARY FOR THIS WEEK AND REGION
region_goals(weekList, "STR1", neDict)
region_goals(weekList, "STR2", mnDict)
region_goals(weekList, "STR3", nlDict)
region_goals函数为:
def region_goals(csv, region, region_dictionary):
firstline = True
for row in csv:
if firstline:
firstline = False
continue
if row[14] == region:
if row[16] not in region_dictionary:
region_dictionary[row[16]] = float(row[6])
else:
region_dictionary[row[16]] += float(row[6])
else:
continue
return region_dictionary
该输出始终与首次使用该功能时期望的一样。在我使用该函数的第二次2次中,返回了空字典。
我确定这是我遗漏的一些小东西,但是我是python的新手,并且一直在努力修复这一问题。预先感谢您的回复。
第一次通过后,您就在CSV文件的末尾,没有任何可读取的内容,因此您需要重新打开它。
同样,用功能就地修改对象也不是最好的主意。每次都最好返回一个新对象。
import csv
from m_functions import region_goals
csvFile = # a file path
regions = ['STR1', 'STR2', 'STR3']
for region in regions:
with csv.reader(open(csvFile)) as weekList:
region_dict = dict()
output = region_goals(weekList, region, region_dict )
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句