According to the answers from this question calling truncate
does not actually move the position of a file.
So my question is, if I truncate
a file to length zero after I read something from it (because I want to write from the beginning) should I / do I have to also call seek(0)
to make sure I am at the beginning of the file?
This seems a little redundant because the file of length zero would have to be at the beginning right?
Yes, you'll have to seek to position 0, truncating 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, then truncating to 0 still left the file pointer at position 6.
Trying to add additional data to such a file results in NULL bytes or garbage data at the start:
>>> 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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With