[Python] Issue during file handling in python while 'write' operation

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    There is a test.txt file which has 'Hello, world' in it already. I am running the code shown below

    with open('test.txt','r+') as f:
    print(f.read(3))
    f.write("wow!")
    f.flush()


    Final content of test.txt: 'Hello, worldwow!'

    My understanding says it should have been 'Helwow!world'.

    Even if I mention f.flush() or not the final content of file remains same.

    I tried implementing this to get more insight:

    with open("test.txt", "r+") as f:
    print(f.tell())
    print(f.read(3))
    print(f.tell())
    f.flush()
    f.write("wow!")
    print(f.tell())


    and the output was:

    0
    Hel
    3
    16


    I could not make out as to why the cursor after write goes to 16. My current Python version is 3.10.0, I tried the same in Google Colab but it's the same.

    Continue reading...

Compartilhe esta Página