Skip to content

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

Closed

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

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    on Feb 6, 2024
  2. added a commit that references this issue on Feb 8, 2024
  3. serhiy-storchaka commented on Feb 8, 2024

    @serhiy-storchaka
    Member

    It is because the C implementation of io.TextIOWrapper.read() uses the read1() method of the underlying binary stream if it is available and the size is specified, and the C implementation of io.BufferedRandom.read1() did not flush the write buffer. #115163 fixes the latter.

  4. added a commit that references this issue on Feb 9, 2024
  5. added 2 commits that reference this issue on Feb 9, 2024
  6. serhiy-storchaka commented on Feb 9, 2024

    @serhiy-storchaka
    Member

    Thank you for your report @blhsing. The issue is now fixed.

  7. added 4 commits that reference this issue on Feb 9, 2024
  8. added 2 commits that reference this issue on Feb 10, 2024
  9. added 2 commits that reference this issue on Feb 10, 2024
  10. added 2 commits that reference this issue on Feb 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

3.11only security fixes3.12only security fixes3.13only 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