File write, weird behaviour

Azizbek Khamdamov azizbek.khamdamov at gmail.com
Sun Feb 19 09:03:55 EST 2023


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