Last modified: Sep 28, 2023 By Alexander Williams

Python: Clear JSON file

Clearing a JSON file in Python typically involves opening the file, truncating its content, and then closing it. Here are some examples of how to clear the contents of a JSON file:

Clear JSON File Using the `truncate()` Method

# Open a JSON file in write mode (creates the file if it doesn't exist)
with open("data.json", "w") as file:
    # Use the `truncate()` method to clear the file's content
    file.truncate()

Output:


# No specific output, but the "data.json" file is now empty
    

Clear JSON File by Opening in Append Mode

# Open a JSON file in append mode ("a" mode)
with open("data.json", "a") as file:
    # Use the `truncate()` method to clear the file's content
    file.truncate()

Output:


# No specific output, but the "data.json" file is now empty
    

Note: The second example opens the file in "append" mode and then truncates it. This approach can be used to clear the contents of an existing JSON file or create an empty one if it doesn't exist.

With these examples, you can easily clear the content of a JSON file in Python to prepare it for new data.