Сбой или ErrorValue в Python - закрытие файлов - PullRequest
0 голосов
/ 12 мая 2018

У меня есть класс, в котором находятся все наши данные, здесь я открываю файл:

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

1 Ответ

0 голосов
/ 12 мая 2018

По моему мнению, вы не должны держать open объекты в переменных класса / экземпляра для передачи. Это станет грязным и легко забыть close явно.

Вместо этого я бы держал имена файлов в переменных и передавал их в функции, которые open и close файлы с помощью 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
...