我正在预处理一个csv文件,并希望输出由字段过滤的csv文件数据组成的3个字典。Python函数只运行一次
的设置是:
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
输出始终如预期的第一次使用的功能。第二次我使用这个函数,返回空字典。
我敢肯定,这是我缺少一些小东西,但我是python新手,一直在努力解决这个问题。预先感谢您的回复。
您已经在第一次调用中迭代了文件,因此后面的调用没有任何可读的内容。您可能需要将调用移动到'weekList = csv.reader(open(csvFile))'到函数中(所以文件被重新打开),或者如果csv.reader类支持,您可以尝试'weekList.seek(0)'它。 –
如果函数返回三个字典,那么显然它会运行三次。 –
不错的尝试阿纳布,但如果你看看上面的内容,在设置过程中会创建三个空字典。 –