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?
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?
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')
If you open the file with mode w
it will overwrite the file if it already exists:
with open('your_file', 'w') as f:
f.write('Some text\n')
This would create a file named your_file
and write to it. If the file already exists, and you have permission to do so, it will overwrite the existing file.
You might also notice that I used open()
within a with
statement (context manager). This ensures that the file will be properly closed when execution leaves the scope of the context manager.
when opening in write mode, you clear the text in the file.
with open() as f:
f.write("")
that'll fix it for you!