Yes, you need to search for position 0, truncation does not update the file pointer:
>>> with open('/tmp/test', 'w') as test: ... test.write('hello!') ... test.flush() ... test.truncate(0) ... test.tell() ... 6 0 6
Writing 6 bytes and then truncating to 0 is still the file pointer at position 6.
Attempting to add additional data to such a file results in NULL bytes or garbage data at the beginning:
>>> with open('/tmp/test', 'w') as test: ... test.write('hello!') ... test.flush() ... test.truncate(0) ... test.write('world') ... test.tell() ... 6 0 5 11 >>> with open('/tmp/test', 'r') as test: ... print(repr(test.read())) ... '\x00\x00\x00\x00\x00\x00world'
source share