Python中的崩溃或错误值-关闭文件

Python中的崩溃或错误值-关闭文件,python,file,valueerror,open-closed-principle,Python,File,Valueerror,Open Closed Principle,我有一个类,所有数据都在其中,在这里我通过以下方式打开一个文件: carIn= open("dataIn.txt","w") carOut= open("dataUit.txt","w") 在另一个类中,我有一个主程序的循环。我在循环中关闭了文件,但它不会再次打开。如果我在循环外关闭它,整个程序就会崩溃。这是我的代码: while startScreen.getstopt() == False: startScreen.start() print("screen start"

我有一个类,所有数据都在其中,在这里我通过以下方式打开一个文件:

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
对象来传递。这将变得混乱,很容易忘记显式地关闭

相反,我会将文件名保存在变量中,并通过
with
语句将它们传递到函数中,这些函数通过
打开
关闭
文件

以下是一个例子:

Files.carIn = 'dataIn.txt'
Files.carOut = 'dataUit.txt'

with open(Files.carIn, 'w') as file_in, open(Files.carOut, 'w') as file_out:
    while startScreen.getstopt() == False:
        # do things with file_in & file_out

这不是答案,只是一个提示。我建议您将
与open一起使用
,这样您就不必担心关闭文件了。你可以阅读更多关于它的内容。此外,您还可以创建一个类来抽象它,例如,您调用
write
方法,该类将打开文件,写入并关闭文件。下面的答案是否有帮助?如果是这样,请随意接受(勾选左侧),或要求澄清。