How to Overwrite a File in Python?

Recently in a Python webinar, someone asked me how to overwrite a file in Python. After researching and experimenting I found two effective ways to achieve this task. In this tutorial, I will explain the important methods with suitable examples and screenshots. Let’s learn more about this topic today.

Overwrite a File in Python

Overwriting files is a common task in programming, especially when you need to update existing data or replace outdated information. Python provides several ways to overwrite files efficiently. By mastering these techniques, you can streamline your workflow and ensure your data remains up to date.

Read How to Rename Files in Python?

Method 1: Use the open() Function with Write Mode

The simplest way to overwrite a file in Python is by using the open() function with the write mode ("w"). Here’s an example:

# Overwriting a file using open() with write mode
with open("customer_data.txt", "w") as file:
    file.write("John Doe, New York\n")
    file.write("Jane Smith, California\n")
    file.write("Michael Johnson, Texas\n")

I executed the above example code and added the screenshot below.

Overwrite a File in Python

In this example, we use the open() function to open the file "customer_data.txt" in write mode. The with statement ensures that the file is properly closed after writing. We then use the write() method to overwrite the file with new customer data specific to the USA.

Check out How to Write a Variable to a File in Python?

Method 2: Use the os Module to Replace the File

Another approach to overwrite a file is by using the os module in Python. This method involves creating a new file with the updated content and then replacing the original file with the new one. Here’s an example:

import os

# Creating a new file with updated content
with open("temp_employee_records.txt", "w") as new_file:
    new_file.write("John Smith, Marketing, New York\n")
    new_file.write("Emily Davis, Sales, California\n")
    new_file.write("David Wilson, Engineering, Texas\n")

# Replacing the original file with the new file
os.replace("temp_employee_records.txt", "employee_records.txt")

I executed the above example code and added the screenshot below.

How to Overwrite a File in Python

In this example, we first create a new file called "temp_employee_records.txt" and write the updated employee records to it. Then, we use the os.replace() function to replace the original file "employee_records.txt" with the newly created file.

Read How to Check if a File is Empty in Python?

Handle Real-World Scenarios

Let’s consider a real-world scenario where you need to overwrite a file containing sales data for different states in the USA. Here’s an example:

# Overwriting sales data for different states
sales_data = {
    "California": 5000,
    "New York": 4500,
    "Texas": 6000,
    "Florida": 4800
}

with open("sales_report.txt", "w") as file:
    for state, sales in sales_data.items():
        file.write(f"{state}: ${sales}\n")

In this example, we have a dictionary called sales_data that contains sales figures for different states. We open the file "sales_report.txt" in write mode and use a loop to iterate over the dictionary. For each state and its corresponding sales amount, we write a formatted string to the file, effectively overwriting its contents.

Check out Python Get File Extension

Conclusion

In this article, I helped you to learn how to overwrite a file in Python. I discussed mainly two methods to accomplish this task such as using the open() function with write mode and leveraging the os module to replace files. I also discussed how to handle a real-world scenario.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.