1

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() 
2
  • 2
    This is not an answer, just a tip. I would suggest you to use with open so you don't need to worry about close the file. You can read more about it here. Also, you can create a class to abstract it, for example, you call the write method, the class will open the file, write and close the file. Commented May 12, 2018 at 13:59
  • Did the below answer help? If so, feel free to accept (tick on left), or ask for clarification. Commented May 16, 2018 at 11:41

1 Answer 1

2

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.