8

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?

Community
  • 1
  • 1
Startec
  • 12,496
  • 23
  • 93
  • 160

1 Answers1

13

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'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343