This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author steven.daprano
Recipients ke265379ke, steven.daprano, terry.reedy
Date 2020-12-26.02:20:17
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
In-reply-to <>
On Fri, Dec 25, 2020 at 01:31:51PM +0000, 施文峰 wrote:

> first test have a problem,you didn’t use r+ mode

I did, I copied your `test()` function exactly, however I did make a 
mistake. I tried again with this:

>>> with open(FILE_PATH, 'r') as f:
...     print(repr(

so you are correct, the file is padded with NUL characters.

Here is a simpler demonstration of the behaviour.


# create a file
with open(FILE_PATH, 'w') as f:

# Truncate using r+ mode.
with open(FILE_PATH, 'r+') as f:
    assert f.tell() == 0
    assert == 'abc\n'
    assert f.tell() == 4  # File position is now at end of file.
    assert f.tell() == 4  # File position has not changed.
    assert == ''  # Nothing remaining to read.
    assert f.tell() == 8
    assert == ''  # Nothing remaining to read.
    # Return the file position to start of file.
    assert == '\0\0\0\0xyz\n'


All the assertions pass.

I think this is standard and correct behaviour. Do you have examples of 
other programming languages that behave differently? PHP seems to do the 
same thing:
Date User Action Args
2020-12-26 02:20:18steven.dapranosetrecipients: + steven.daprano, terry.reedy, ke265379ke
2020-12-26 02:20:18steven.dapranolinkissue42733 messages
2020-12-26 02:20:17steven.dapranocreate