Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage in file after truncate(0) in Python

Tags:

python

Assume there is a file test.txt containing a string 'test'.

Now, consider the following Python code:

f = open('test', 'r+')
f.read()
f.truncate(0)
f.write('passed')
f.flush();

Now I expect test.txt to contain 'passed' now, however there are additionally some strange symbols!

Update: flush after truncate does not help.

like image 348
Roman Byshko Avatar asked Jan 20 '12 17:01

Roman Byshko


1 Answers

Yeah, that's true that truncate() doesn't move the position, but said that, is simple as death:

f.read()
f.seek(0)
f.truncate(0)
f.close()

this is perfectly working ;)

like image 157
Andrea Rabbaglietti Avatar answered Sep 21 '22 14:09

Andrea Rabbaglietti