If I truncate a file to zero in Python 3 do I also need to seek to position zero?

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?

Answers


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'

Need Your Help

Center horizontally and/or vertically with 9 patch in Android

java android relativelayout nine-patch

I can't find a topic talking about my problem which seems to me standard ... And that make me think it is not possible. But I give a try.

RubyMotion: The operation couldn’t be completed. (com.apple.InterfaceBuilder error 2001.)

interface-builder xib nib rubymotion

In the latest version of my application I started seeing this error message during compile which would just bring