Christophe Beke
Christophe Beke

Reputation: 11

Crashing or ErrorValue in Python - closing files

I have a class where all of our data is in, here I open a file by:

carIn= open("dataIn.txt","w")
carOut= open("dataUit.txt","w")

In another class I have a loop for the main program. I closed my file in the loop but it won't open again. If I close it outside the loop, the entire program crashes. This is my code:

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

Upvotes: 1

Views: 273

Answers (1)

jpp
jpp

Reputation: 164663

In my opinion, you shouldn't be holding open objects in class / instance variables to pass around. This will become messy and it's easy to forget to close explicitly.

Instead, I would hold the filenames in variables and pass them into functions which open and close files via with statements.

Here is an example:

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

Upvotes: 2

Related Questions