Python - How To Clear a File in Python

ID : 422

viewed : 222

Tags : PythonPython File

vote vote


In this tutorial, we will introduce how to clear a file in Python.

Use the truncate() Function to Clear the Contents of a File in Python

The truncate() method in the Python file handling allows us to set the size of the current file to a specific number of bytes. We can pass the desired size to the function as arguments. To truncate a file, we need to open it in append or read mode. For example.

with open("sample.txt", 'r+') as f:     f.truncate(4) 

Notice that the file is opened in read and write mode. The above code resizes the sample file to 4 bytes. To clear all the contents of a file, we simply pass 0 to the function as shown below.

with open("sample.txt", 'r+') as f:     f.truncate(0) 

This method is handy when we want to read a file and remove its contents afterward. Also, note that if one needs to write to this file after erasing its elements, add to move to the beginning of the file after the truncate() function.

Use the write Mode to Clear the Contents of a File in Python

In Python, when we open a file in write mode, it automatically clears all the file content. The following code shows how.

with open("sample.txt",'w') as f:     pass 

When we open the file in write mode, it automatically removes all the contents from the file. The pass keyword here specifies that there is no operation executed.

Another method of achieving the same is shown below:

f = open("sample.txt","w") f.close() 

  • Related HOW TO?