'How do I clear a .txt file with the open() function?
I have a simple program which opens a file and replaces text. However, I want the program to clear the file, then save what needs to be saved.
How do I do that? Or is there a simpler way to do so?
Solution 1:[1]
When you open a file in 'w' mode, it's content would be erased.
from doc - 'w' for only writing (an existing file with the same name will be erased)
Just open file as
open(file, 'w')
Solution 2:[2]
when opening in write mode, you clear the text in the file.
with open() as f:
f.write("")
that'll fix it for you!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AlokThakur |
| Solution 2 | Crashberry py |
