4

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Can you show some code of what you have attempted? – pczeus Feb 28 '16 at 03:50
  • 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 Feb 08 '22 at 12:41

3 Answers3

7

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')
AlokThakur
  • 3,599
  • 1
  • 19
  • 32
7

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.

mhawke
  • 84,695
  • 9
  • 117
  • 138
-1

when opening in write mode, you clear the text in the file.

with open() as f:
    f.write("")

that'll fix it for you!