From what I have seen, there are 2 ways to print to a file:
Method 1
file = open('myfile.txt', 'a')
file.write('sup')
# LATER ON
file.write('yo')
# AT THE END
file.close()
Method 2
with open('myfile.txt', 'a') as f:
f.write('sup')
# LATER ON
with open('myfile.txt', 'a') as f:
f.write('yo')
The problem with the first method, is that if the program were to end abruptly, the file does not close and is not saved. Because of this, I am currently using with and reopening the file everytime I want to print to it. However, I realize this may be a bad idea considering that I append to this file almost every 5 seconds. Is there a major performance hit in reopening the file with "with" before printing every time? And if so, how should I handle abrupt endings that result in the file not being closed using the first method.