Does anyone know how to clear a file's contents on python? Thank you.
Asked
Active
Viewed 78 times
-1
-
As in, replace the data of a file with essentially nothing? – h0r53 Aug 17 '20 at 19:09
-
Does this answer your question? [How to erase the file contents of text file in Python?](https://stackoverflow.com/questions/2769061/how-to-erase-the-file-contents-of-text-file-in-python) – mkrieger1 Aug 17 '20 at 19:21
-
yes thank you it works like a charm – crvcio Aug 17 '20 at 19:35
2 Answers
1
Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:
open(filename, 'w').close()

Robindpw
- 58
- 7
0
You can use truncate function on the file object:
file_object = open('test.txt','r+')
file_object.truncate()
file_object.close()

Tomato Master
- 496
- 3
- 10