[Python] Why does file.write() in "r+" mode not overwrite old content as expected?

Discussão em 'Python' iniciado por Stack, Abril 6, 2025.

  1. Stack

    Stack Membro Participativo

    I expected the following Python code to overwrite part of the file:

    #PYTHON
    # File "rplus.txt" initially contains: Hello, world!
    with open("rplus.txt", "r+") as file:
    print(file.read(5)) # Outputs: Hello
    file.write(", Python!") # Attempt to overwrite the rest
    file.seek(0)
    print(file.read()) # Unexpected output



    But instead of getting:

    Hello

    Hello, Python!

    I got:

    Hello

    Hello, world!, Python!

    I thought file.write() in "r+" mode would start writing at the current cursor and overwrite existing characters. Why is the original "world!" still there? Shouldn't it be overwritten?

    Continue reading...

Compartilhe esta Página