HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat N Strings
      • Python Example Code to Concat 2 Numbers
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
    • Modules and Libraries
      • Python Code to Load .SO File (and Invoke a Function)
      • Python Code for Automation using BDD
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Python Code to Clear Contents of a File

In Python, managing file contents is a common task, often requiring the ability to clear existing data from a file.

This article shows 2 effective methods for achieving this: one utilizing the truncate() method to directly clear the contents, and the other leveraging the inherent behavior of opening a file in write mode to achieve the same result.

Using these methods, Python developers can efficiently manipulate file contents, ensuring their applications maintain clean and up-to-date data storage.

Method 1 – Using truncate() method

Clearing the contents of the file can be easily done using truncate() built-in function.

def clear_file_contents(file_path):
    try:
        with open(file_path, 'w') as file:
            file.truncate(0)
        print(f"Contents of '{file_path}' cleared successfully.")
    except Exception as e:
        print(f"An error occurred: {e}")

Let’s use the above function to clear file contents:

# Example usage:
file_path = "example.txt"  # Specify the path to your file
clear_file_contents(file_path)

Let’s see the detailed summary of the above code.

  • The code defines a function `clear_file_contents` that takes a single argument `file_path`, which is the path to the file whose contents need to be cleared.
  • Inside the function, it tries to open the file specified by `file_path` in write mode (`’w’`). Opening a file in write mode truncates it to zero length if it exists, or creates a new empty file if it doesn’t exist.
  • Once the file is opened, the `file.truncate(0)` method is called. This method truncates the file to the specified size, which in this case is `0`, effectively clearing its contents.
  • After truncating the file, a message is printed to indicate that the contents of the file have been cleared successfully.
  • If any errors occur during the process (e.g., if the file cannot be opened or truncated), an exception is caught, and an error message is printed.

Method 2 – Using simple open() method

Let’s see another method that achieves the same goal of clearing the contents of a file, but using a slightly different approach but very simple.

import os

def clear_file_contents(file_path):
    try:
        with open(file_path, 'w'):
            pass  # Using pass to do nothing
        print(f"Contents of '{file_path}' cleared successfully.")
    except Exception as e:
        print(f"An error occurred: {e}")

Now lets see how to call the above function:

# Example that works
file_path = "example.txt"  # Specify the path to your file
clear_file_contents(file_path)

Let me explain this method in detail.

  • The function `clear_file_contents` takes a single argument `file_path`, which is the path to the file whose contents need to be cleared.
  • Inside the function, it tries to open the file specified by `file_path` in write mode (`’w’`). Unlike the previous method, it doesn’t explicitly truncate the file. When a file is opened in write mode in Python, it automatically truncates the file to zero length if it exists, or creates a new empty file if it doesn’t exist.
  • Instead of calling `file.truncate(0)`, this method simply uses the `pass` statement inside the `with` block. The `pass` statement in Python is a null operation; nothing happens when it is executed. So, in this case, it effectively does nothing inside the `with` block.
  • After the `with` block, a message is printed to indicate that the contents of the file have been cleared successfully.
  • Similar to the previous method, if any errors occur during the process (e.g., if the file cannot be opened or truncated), an exception is caught, and an error message is printed.

Both methods achieve the same result of clearing the contents of a file, but they use slightly different approaches to accomplish it. You can pick the one you find it simple.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas

No luck finding what you need? Contact Us

Previously
Python Code to Read Specific Line from a File
Up Next
Python Code to Count and List Files in a Directory
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2025 Happiom. All Rights Reserved.