我有一个类,其中包含所有数据,在这里我打开一个文件:
carIn= open("dataIn.txt","w")
carOut= open("dataUit.txt","w")
在另一个类中,我有一个主程序的循环。我在循环中关闭了文件,但它不会再打开了。如果我在循环外关闭它,整个程序就会崩溃。这是我的密码:
while startScreen.getstopt() == False:
startScreen.start()
print("screen start")
screen = Screen(wereld.getIntersection())
startSimulatiion()
print("Simulatiion start:")
for x in Files.listIn:
Files.carIn.write(str(x) + "\n")
for x in Files.listOut:
Files.carOut.write(str(x) +"\n")
result= Resultaten()
Files.calculatedRatio= result.calculateRatio()
print(Files.calculatedRatio)
if screen.startScreen == True:
Files.carIn.write("\n")
Files.carIn.write("\n")
Files.carIn.write("\n")
Files.carOut.write("\n")
Files.carOut.write("\n")
Files.carOut.write("\n")
Files.carIn.close()
Files.carOut.close()
在我看来,不应该在类/实例变量中持有
open
对象来传递。这将变得混乱,很容易忘记显式地close
。你知道吗相反,我将文件名保存在变量中,并通过
with
语句将它们传递到函数中,这些函数包含open
和close
文件。你知道吗举个例子:
相关问题 更多 >
编程相关推荐