File write, weird behaviour

Axy axy at declassed.art
Sun Feb 19 11:57:02 EST 2023


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()

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?


More information about the Python-list mailing list