Reputation: 8457
I'm in the Python shell and I'm trying to understand the basics. Here is what I have typed:
doc = open('test.txt', 'w') # this opens the file or creates it if it doesn't exist
doc.write('blah blah')
doc.truncate()
I understand the first line. However, in the second line, isn't it supposed to write 'blah blah' to the file? It doesn't do that. However, when I run a truncate
function to the file, 'blah blah' suddenly shows up. Can someone explain to me how this logic works?
I thought truncate
was supposed to erase the contents of the file? Why does it make the previous write
line show up?
Upvotes: 2
Views: 1715
Reputation: 476
If you don't specify size parameter. The function take current position.
If you want to erase content of file:
doc = open('test.txt', 'w') # this opens the file or creates it if it doesn't exist
doc.write('blah blah')
doc.truncate(0)
or better:
with open('test.txt', 'w') as doc:
doc.write('blah blah')
doc.truncate(0)
Upvotes: 0
Reputation: 394965
Same as you with the context manager instead:
with open('test.txt', 'w') as doc:
doc.write('blah blah')
# doc.truncate()
The above will truncate to the current position, which is at the end of the file, meaning it doesn't truncate anything.
Do this instead, it will truncate the file at the 0th byte, effectively clearing it.
doc.truncate(0)
I see from your comments that you may still be having trouble, trouble that may be solved by using the context manager:
>>> def foofile():
... with open('/temp/foodeleteme', 'w') as foo:
... foo.write('blah blah blah')
... foo.truncate(0)
... with open('/temp/foodeleteme') as foo:
... print foo.read()
...
>>> foofile()
prints nothing.
Upvotes: 1
Reputation: 59110
From the manual:
file.truncate([size])
[...] The size defaults to the current position [...]
so as you have opened and written to the file, the current position is the end of the file. Basically, you are truncating from the end of the file. Hence the absence of effect other than actually flushing the buffers, and getting the text written to disk. (truncate
flushes before truncating)
Try with truncate(0)
; that will empty the file.
Upvotes: 3