On 2/19/2023 11:57 AM, Axy via Python-list wrote:
Looks like the data to be written is buffered, so actual write takes
place after readlines(), when close() flushes buffers.
See io package documentation, BufferedIOBase.
The solution is file.flush() after file.write()
Another possibility, from the Python docs:
"...TextIOWrapper (i.e., files opened with mode='r+') ... To disable
buffering in TextIOWrapper, consider using the write_through flag for
io.TextIOWrapper.reconfigure()"
Also from the docs:
"Warning: Calling f.write() without using the with keyword or calling
f.close() might result in the arguments of f.write() not being
completely written to the disk, even if the program exits successfully."
I realize that in the example, close() was called ... but not
immediately after the write().
Can't deny, such a behaviour looks utterly weird. Try to avoid designing
your software this way.
Axy.
On 19/02/2023 14:03, Azizbek Khamdamov wrote:
Example 1 (works as expected)
file = open("D:\Programming\Python\working_with_files\cities.txt",
'r+') ## contains list cities
# the following code adds new record to the beginning of the file,
expected behaviour
file.write("new city\n")
file.close()
Example 2 (weird behaviour)
file = open("D:\Programming\Python\working_with_files\cities.txt",
'r+') ## contains list cities
# the following code DOES NOT add new record TO THE BEGINNING of the
file IF FOLLOWED BY readline() and readlines()# Expected behaviour:
new content should be added to the beginning of the file (as in
Example 1)
file.write("new city\n")
file.readlines()
file.close()
I could not find anything in documentation to explain this strange
behaviour. Why is this happening?
--
https://mail.python.org/mailman/listinfo/python-list