To clear the contents of a file in Python, the easiest way is to open the file in write mode and do nothing.

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

Another way you can erase all contents in a file is with the truncate() function.

with open("example.txt",'w') as f:
    f.truncate(0)

If you want to clear only certain lines from a file, you can use the following method.

with open("example.txt",'r+') as f:
    lines = f.readlines()

    f.seek(0)
    f.truncate(0)

    f.writelines(lines[5:])  #removes first 5 lines from file

When working with files in Python, the ability to easily be able to modify and change the file content can be useful.

One such situation is if you want to clear a file and delete all of the contents in the file.

To clear the contents of a file in Python, the easiest way is to open the file in write mode and do nothing.

Below shows you how to delete all of the contents from a file in Python.

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

Using truncate() to Clear File Contents in Python

You can also use the truncate() function to clear a file and remove all the content in a file.

Below shows you how to remove everything from a file with truncate() in Python.

with open("example.txt",'w') as f:
    f.truncate(0)

Remove Specific Lines from File in Python

If you want to remove specific lines from a file, then you can do the following.

with open("example.txt",'r+') as f:
    lines = f.readlines()

    f.seek(0)
    f.truncate(0)

    f.writelines(lines[5:])  #removes first 5 lines from file

Hopefully this article has been helpful for you to learn how to clear a file in Python.

Categorized in:

Python,

Last Update: March 11, 2024