The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5

--

Chapters
00:00 How To Erase The File Contents Of Text File In Python?
00:10 Accepted Answer Score 482
00:23 Answer 2 Score 46
00:38 Answer 3 Score 39
01:12 Answer 4 Score 24
01:23 Thank you

--

Full question
https://stackoverflow.com/questions/2769...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 482


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+



ANSWER 2

Score 46


Opening a file in "write" mode clears it, you don't specifically have to write to it:

open("filename", "w").close()

(you should close it as the timing of when the file gets closed automatically may be implementation specific)




ANSWER 3

Score 39


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




ANSWER 4

Score 24


As @jamylak suggested, a good alternative that includes the benefits of context managers is:

with open('filename.txt', 'w'):
    pass