Reputation: 1449
Can something wrong happen with the following implementation?
def ReadFromFile(file_name):
return [line for line in open(file_name)]
def AppendToFile(new_line, file_name):
open(file_name, 'a').write(new_line)
I am not explicitly calling close()
method after reading / writing to the file. My understanding is that semantically the program has to behave as if the file is always closed at the end of each function.
Can the following use of these functions give unexpected results, e.g.
original_lines = ReadFromFile("file.txt")
for line in original_lines:
AppendToFile(line, "file.txt")
modified_lines = ReadFromFile("file.txt")
I would expect e.g. len(modified_lines) == len(original_lines) * 2
. Can that ever not be the case?
Upvotes: 0
Views: 52
Reputation: 1163
When we write onto a file using any of the write functions. Python holds everything to write in the file in a buffer and pushes it onto the actual file on the storage device either at the end of the python file or if it encounters a close()
function.
Also if we opened another file with same file object then the first file will be closed by python for example:
file_object1 = open(file1,'r')
file_object1 = open(file2, 'r')
Here in this scenario also file1 will be automatically closed
So if the file terminates in between then the data is not stored in the file. So I would suggest two options:
use with
because as soon as you get out of the block or encounter any exception it closes the file,
with open(filename , file_mode) as file_object:
do the file manipulations........
or you can use the flush()
function if you want to force python to write contents of buffer onto storage without closing the file.
file_object.flush()
For Reference: https://lerner.co.il/2015/01/18/dont-use-python-close-files-answer-depends/
Upvotes: 1