我正在将 4 个 CSV 文件读入内存中的 4 个不同对象。前 3 次,它工作....但第四次失败,说: ValueError: I/O operation on closed file
我导入这些:
import sys
import time
import random
import csv
import ast
这是我的代码:
csvPath = "../../../MegaBits-Data/"
ConditionType = "MBConditionType.csv"
SpeciesType = "MBMegaBitSpecies.csv"
StatusType = "MBStatusEffect.csv"
MoveType = "MBMoveType.csv"
#loading conditions
print "loading '"+str(csvPath)+str(ConditionType)+"' into Memory"
fpReader = open(str(csvPath)+str(ConditionType))
cr = csv.reader(fpReader)
counter = 0
for row in cr:
if(counter == 0):
counter+=1
continue
Conditions[row[0]] = {"type":row[1],"when":row[2],"durationRange":row[3],"likelihood":row[4],"likelihoodChange":row[5],"uuid":row[8]}
fpReader.close()
#loading Species
print "loading '"+str(csvPath)+str(SpeciesType)+"' into Memory"
fpReader = open(str(csvPath)+str(SpeciesType))
cr = csv.reader(fpReader)
counter = 0
for row in cr:
if(counter==0):
counter+=1
continue
Species[row[1]] = MegabitSpecies(row)
fpReader.close()
#loadingStatuses
print "loading '"+str(csvPath)+str(StatusType)+"' into Memory"
fpReader = open(str(csvPath)+str(StatusType))
cr = csv.reader(fpReader)
counter = 0
for row in cr:
if(counter == 0):
counter+=1
continue
Statuses[row[0]] = {"tar":row[1],"tarVal":row[2],"tarValChange":row[3],"needsTarget":row[4], "tarChanges":row[5], "conditionType":row[6], "uuid":row[7]}
fpReader.close()
#load Moves
下一部分失败了:
print "loading '"+str(csvPath)+str(MoveType)+"' into Memory"
open(str(csvPath)+str(MoveType)) as fpReader:
#fpReader = open(str(csvPath)+str(MoveType))
cr = csv.reader(fpReader)
counter = 0
for row in cr:
if(counter==0):
counter+=1
continue
Moves[row[0]] = {"typeObject":row[1],"baseLevel":row[2], "baseAttack":row[3],"baseAccuracy":row[4],"targetsOpponent":row[5],"primaryStatObject":row[6],"spriteSheetName":row[7],"statusEffects":row[8],"uuid":row[9]}
fpReader.close()
它关闭 fpReader,然后打开一个新的,并将其读入 cr。我看不到文件将在哪里关闭。
新守则
with open(str(csvPath)+str(StatusType)) as fpReader:
#fpReader = open(str(csvPath)+str(StatusType))
cr = csv.reader(fpReader)
counter = 0
for row in cr:
if(counter == 0):
counter+=1
continue
Statuses[row[0]] = {"tar":row[1],"tarVal":row[2],"tarValChange":row[3],"needsTarget":row[4], "tarChanges":row[5], "conditionType":row[6], "uuid":row[7]}
fpReader.close()
它在线上失败:
for row in cr:
说:
Traceback (most recent call last):
File "battleSystem.py", line 312, in <module>
main(sys.argv[1:])
File "battleSystem.py", line 22, in main
LoadCSVs()
File "battleSystem.py", line 62, in LoadCSVs
for row in cr:
ValueError: I/O operation on closed file