91

In the Unix shell I can do this to empty a file:

cd /the/file/directory/
:> thefile.ext

How would I go about doing this in Python?

Is os.system the way here, I wouldn't know how since I would have to send 2 actions after each other i.e. the cd and then the :>.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Adergaard
  • 913
  • 1
  • 6
  • 4
  • 1
    Shouldn't opening the file with a mode of "w" do this, i.e. `open("/the/path/thefile.ext","w")`? – Ulrich Schwarz Feb 06 '11 at 15:45
  • @Adergaard: I'm not prepared to claim categorically that there are no border cases (e.g. networked file systems) where it will fail. I don't know if you are in one of those cases, and had already tried, and it didn't work for you. – Ulrich Schwarz Feb 06 '11 at 16:06
  • 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:40

2 Answers2

197

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()
rumpel
  • 7,870
  • 2
  • 38
  • 39
  • Would there be a problem if the file is constantly written to (it is a log file that is written to every second) – Adergaard Feb 06 '11 at 15:47
  • 1
    @Adergaard Typically not. If the file is already existing, it will not be created, but the same file will be used and truncated. If the logging process continues to write to the file, it will also appear in that file then. However, in combination with file operations based on `seek` or `tell`, weird things may happen. – rumpel Feb 06 '11 at 15:53
  • weird, this just seems not to be the case. – Andy Hayden Oct 07 '14 at 21:41
  • Didn't work for me when rewriting file in a for loop. I used os.remove("filename") and then file1 = open("filename", "w") – Steven2163712 Jan 16 '19 at 16:27
42

Alternate form of the answer by @rumpel

with open(filename, 'w'): pass
jamylak
  • 128,818
  • 30
  • 231
  • 230