Thanks to visit codestin.com
Credit goes to github.com

Skip to content

readline() causes output to be written at eof unless seek() is used #113439

Closed as duplicate of#82891
@ghost

Description

Bug report

Bug description:

# Add a code block here, if required

In python3 it seems that there is a bug with the readline() method.

I have a file txt.txt that contains two lines:

1234567890
abcdefghij

I then run the following code:

g = open("txt.txt","r+")
g.write("xxx")
g.flush()
g.close()

It modifies the file as expected:

xxx4567890
abcdefghij

I then run the following code:

g = open("txt.txt","r+")
g.readline()    
Out[99]: 'xxx4567890\n'
g.tell()
Out[100] 12
g.write("XXX")
g.flush()
g.close()

I get the following:

xxx4567890
abcdefghij
XXX

Why is "XXX" being written to the end of the file instead of just after the first line?

If I run the following:

g = open("txt.txt","r+")
g.readline()    
Out[99]: 'xxx4567890\n'
g.tell()
Out[100] 12
g.seek(12)
g.tell()
g.write("XXX")
g.flush()
g.close()

I get:

xxx4567890
XXXdefghij
XXX

seems like this is a bug in readline() - it says the cursor is at 12 but writes at EOF unless I use seek()

CPython versions tested on:

3.11

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)topic-IOtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions