If I truncate a file to zero in Python 3, do I also need to search for a null position?

According to the answers of this question, calling truncate does not actually move the file position.

So my question is: if I truncate file to zero after I read something from it (because I want to write from the very beginning), should I / also call seek(0) to make sure that I am at the beginning of the file?

Does this seem a little redundant because the zero-length file should be at the beginning on the right?

+6
source share
1 answer

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' 
+9
source

All Articles