How to Clear the Contents of a File in Python?

Estimated read time 1 min read

To clear the contents of a file in Python, you can open the file in “write” mode and truncate its content. Here’s an example:

file_path = "path/to/file.txt"

# Open the file in write mode and truncate its content
with open(file_path, "w") as file:
    file.truncate(0)

In this example, file_path represents the path to the file you want to clear. The file is opened in “write” mode using the open() function. By specifying "w" as the mode, the file is opened for writing, and if the file already exists, its content is truncated (i.e., cleared).

The truncate() method is called on the file object, passing 0 as the size argument. This effectively sets the file’s size to zero, removing all its contents.

Using the with statement ensures that the file is properly closed after the operation is complete, even if an exception occurs.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply