How to erase the file contents of text file in Python?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3
--
Chapters
00:00 Question
00:19 Accepted answer (Score 442)
00:37 Answer 2 (Score 42)
00:59 Answer 3 (Score 37)
01:42 Answer 4 (Score 21)
01:58 Thank you
--
Full question
https://stackoverflow.com/questions/2769...
Answer 2 links:
[A simple example]: http://www.tutorialspoint.com/python/fil...
Answer 3 links:
[benefits of context managers]: https://stackoverflow.com/questions/3012...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 482
In Python:
open('file.txt', 'w').close()
Or alternatively, if you have already an opened file:
f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
ANSWER 2
Score 46
Opening a file in "write" mode clears it, you don't specifically have to write to it:
open("filename", "w").close()
(you should close it as the timing of when the file gets closed automatically may be implementation specific)
ANSWER 3
Score 39
Not a complete answer more of an extension to ondra's answer
When using truncate() ( my preferred method ) make sure your cursor is at the required position.
When a new file is opened for reading - open('FILE_NAME','r') it's cursor is at 0 by default.
But if you have parsed the file within your code, make sure to point at the beginning of the file again i.e truncate(0)
By default truncate() truncates the contents of a file starting from the current cusror position.
ANSWER 4
Score 24
As @jamylak suggested, a good alternative that includes the benefits of context managers is:
with open('filename.txt', 'w'):
pass