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

Skip to content

io.TextIOWrapper.read does not flush the underlying write buffer when given a size argument #115059

Closed
@blhsing

Description

@blhsing

Bug report

Bug description:

As reported by the StackOverflow question:
https://stackoverflow.com/questions/76142400/python-file-write-stuck-in-append-mode-when-read-has-byte-count-as-parameter

In the code below, when f.read is not given an argument, the pending content in the write buffer gets flushed so the output is ***s is a line as expected.

with open("new.txt", 'w+') as f:
    f.write("this is a line")

with open("new.txt", 'r+') as f:
    f.write("***")
    f.read()  # << note here
    f.seek(0)
    print(f.read()) # outputs: ***s is a line

But when f.read is given a size argument, it is apparent that the underlying write buffer is not flushed immediately, causing the pending content to be written at the end of the file, rendering an output of this is a line*** instead:

with open("new.txt", 'w+') as f:
    f.write("this is a line")

with open("new.txt", 'r+') as f:
    f.write("***")
    f.read(1)  # << note here
    f.seek(0)
    print(f.read()) # outputs: this is a line***

This issue occurs only with the C implementation of io.TextIOWrapper since the code above would work as expected if it is prepended with:

from _pyio import open

CPython versions tested on:

3.8, 3.11

Operating systems tested on:

Linux, Windows

Linked PRs

Metadata

Metadata

Labels

3.11only security fixes3.12only security fixes3.13bugs and security fixestopic-IOtype-bugAn unexpected behavior, bug, or error

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions