我正在将4个CSV文件读入4个不同的对象到内存中。前3次,它有效....但第四次失败,说: ValueError:关闭文件的I / O操作
我导入这些:
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
答案 0 :(得分:2)
Python幸运地使文件I / O比你制作它简单得多。
with open(file, mode) as source:
#do stuff with source
如果你做这样的文件访问,你不应该担心这种东西。