简体   繁体   中英

Python: 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?
Thanks for your help :3

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 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')

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

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

that'll fix it for you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM