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 <20201226022004.GU28254@ando.pearwood.info>
In-reply-to <1608903111.41.0.800279345559.issue42733@roundup.psfhosted.org>
Content
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(f.read()))
... 
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00{"how_dare_you": 
"how_dare_you"}'

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

Here is a simpler demonstration of the behaviour.

```
FILE_PATH = 'example.data'

# create a file
with open(FILE_PATH, 'w') as f:
    f.write('abc\n')

# Truncate using r+ mode.
with open(FILE_PATH, 'r+') as f:
    assert f.tell() == 0
    assert f.read() == 'abc\n'
    assert f.tell() == 4  # File position is now at end of file.
    f.truncate(0)
    assert f.tell() == 4  # File position has not changed.
    assert f.read() == ''  # Nothing remaining to read.
    f.write('xyz\n')
    f.flush()
    assert f.tell() == 8
    assert f.read() == ''  # Nothing remaining to read.
    # Return the file position to start of file.
    f.seek(0)
    assert f.read() == '\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:

https://www.php.net/manual/en/function.ftruncate.php
History
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