Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

file-io

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?

like image 557
Startec Avatar asked Jul 25 '15 08:07

Startec


1 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'
like image 144
Martijn Pieters Avatar answered Oct 12 '22 23:10

Martijn Pieters