Reputation: 47
fileN = open("test1.txt", 'w')
print('255 255 255', file = fileN)
#fileN.close()
The file "test1.txt" would be empty without the final closing statement.
def foo():
fileN = open("test2.txt", 'w')
print('255 255 255', file = fileN)
#fileN.close()
foo()
However, if I wrote the code in a function and then call it, the file would be written successfully even without the closing the statement.
So I have 2 questions: Does a file have to be closed to be written? Will python close the file automatically when the function is over?
Upvotes: 1
Views: 5890
Reputation: 307
If you can't remember to close the file after writing to it, use this instead.
with open(filename):
When you use with open()
, Python will automatically close the file for you at the end of execution.
Python will close the file even if you do not invoke file.close()
, but the time it takes is unpredictable, it can slow your program down. And the edit you do to the opened file will not be applied until the file is closed by python eventually.
If you want the data to appear in the actual file immediately after the write()
, you can do a file.flush()
. Otherwise, it will automatically do for you during file.close()
.
Upvotes: 2
Reputation: 618
Usually, the file closes when the function is finished. There are some cases where this isn't true, but otherwise you don't need to worry about it too much.
Upvotes: 0