File write, weird behaviour
MRAB
python at mrabarnett.plus.com
Sun Feb 19 12:18:54 EST 2023
On 2023-02-19 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?
It works correctly if you use file.flush() or file.tell() before
switching from writing to reading.
More information about the Python-list
mailing list