Python关闭文件时崩溃或ErrorValue

2024-09-29 22:28:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类,其中包含所有数据,在这里我打开一个文件:

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()

Tags: 文件intxtforfilesresultopenscreen
1条回答
网友
1楼 · 发布于 2024-09-29 22:28:24

在我看来,不应该在类/实例变量中持有open对象来传递。这将变得混乱,很容易忘记显式地close。你知道吗

相反,我将文件名保存在变量中,并通过with语句将它们传递到函数中,这些函数包含openclose文件。你知道吗

举个例子:

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

相关问题 更多 >

    热门问题