This post will discuss how to delete the contents of a file in Python. In order words, truncate the file to 0 bytes.

1. Using 'w' mode

The simplest solution is to open the file in w mode, which opens it for writing. The file is created if it does not exist; otherwise, it is truncated. Here’s what the code would look like:

Download Code

 
The above code explicitly closes the file handler with the close() function. This can be avoided using the with statement, which automatically closes the file handler when done with it. Here’s an example of using the with statement:

Download Code

2. Using truncate() function

Alternatively, you can open a file for updating (reading and writing) without truncating it. This can be done using the r+ mode, which neither deletes the content nor creates a new file if it doesn’t exist. Then to truncate the file to 0 bytes, use the truncate() function.

Download Code

That’s all about deleting the contents of a file in Python.