[Python] seek() and tell() in text mode, file handling python

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

  1. Stack

    Stack Membro Participativo

    I learnt that f.tell() returns an integer giving the file object’s current position in the file represented as number of bytes from the beginning of the file when in binary mode and an opaque number when in text mode. but here tell() is changing the output anyone know how?

    with open(r"C:\Users\Harshit\Desktop\file15.txt","w+") as f:
    a=f.read()
    f.write("hello1")
    f.write("hello2last")
    f.seek(0,0)
    f.write("HELLO3")
    f.write("HELLO3")
    print(f.read(1))
    f.write("added")
    f.seek(0,0)
    f.write("55555")
    print(a,type(a))


    output:

    555551hello2lastHELLO3HELLO3added


    also using tell() before read(1) i.e print(f.tell(),f.read(1)) changes output to :

    555553HELLO3lastadded


    whereas in binary mode it gives the perfect output as expected

    555553HELLO3ladded


    why i m getting faulty outputs in text mode?

    Continue reading...

Compartilhe esta Página