5

Why do these two very similar codes behave so differently?

Code 1:

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())

Output: ***s is a line

Code 2:

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())

Output: this is a line***

Python version: Python 3.10.6 (tags/v3.10.6:9c7b4bd, Aug 1 2022, 21:53:49) [MSC v.1932 64 bit (AMD64)] on win32

10
  • 1
    I can repro this on MacOS. (Python 3.11.0 (main, Nov 15 2022, 05:43:36) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin) Commented Apr 30, 2023 at 17:03
  • 1
    @MisterMiyagi Thanks. I tried on Cygwin and WSL2. Same bug. Commented Apr 30, 2023 at 17:07
  • 1
    Same on Python 3.9.6 (default, Sep 24 2021, 19:09:16) [GCC 7.4.0] on linux. It seems to be platform independent. Commented Apr 30, 2023 at 17:12
  • 2
    Good find. I've submitted a bug report for this issue. Commented Feb 6, 2024 at 3:29
  • 1
    Note that this bug is specific to the C implementation of the io module, so until the bug is fixed you can work around it by using the Python implementation of the io module instead by adding from _pyio import open. Commented Feb 6, 2024 at 3:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.