Steven D'Aprano <steve+pyt...@pearwood.info> added the comment: 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 ---------- title: io's r+ mode truncate(0) -> [issue] io's r+ mode truncate(0) _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue42733> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com