How to erase the file contents of text file in Python?


I have text file which I want to erase in Python. How do I do that?

2/26/2017 6:58:27 PM

Accepted Answer

In python:

open('file.txt', 'w').close()

Or alternatively, if you have already an opened file:

f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+

In C++, you could use something similar.

6/28/2018 8:38:20 PM

Not a complete answer more of an extension to ondra's answer

When using truncate() ( my preferred method ) make sure your cursor is at the required position. When a new file is opened for reading - open('FILE_NAME','r') it's cursor is at 0 by default. But if you have parsed the file within your code, make sure to point at the beginning of the file again i.e truncate(0) By default truncate() truncates the contents of a file starting from the current cusror position.

A simple example

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow