Overwrite an Existing File in Python

In Python, you can overwrite an existing file by opening it in write mode ('w') or append mode ('a'). The write mode completely replaces the content of the file, while append mode adds content at the end. In this tutorial, we will explore different methods to overwrite a file in Python with examples.


Examples for Overwriting Files

1. Overwriting a File Using Write Mode

Using open() with mode 'w' allows us to overwrite the entire content of the file. If the file does not exist, it will be created.

In this example, we overwrite an existing file example.txt with the following content.

main.py

</>
Copy
# Open the file in write mode ('w')
with open("example.txt", "w") as file:
    file.write("This is the new content of the file.")

print("File overwritten successfully.")

Explanation:

  1. We use open("example.txt", "w") to open the file in write mode.
  2. The write() method replaces the existing content with the new text "This is the new content of the file.".
  3. The file is automatically closed after exiting the with block.

Output:

example.txt with updated content:

2. Overwriting a File Using Path.write_text() from pathlib

The pathlib module provides a simple way to overwrite a file using Path.write_text().

main.py

</>
Copy
from pathlib import Path

# Define file path
file_path = Path("example.txt")

# Overwrite the file content
file_path.write_text("Overwriting file using pathlib.")

print("File overwritten successfully.")

Explanation:

  1. Path("example.txt") creates a file path object.
  2. write_text() writes new content to the file, replacing any existing content.
  3. The function automatically creates the file if it does not exist.

Output:

example.txt with updated content:

3. Overwriting a File Using File Truncate Method

You can overwrite a file by opening it in read-write mode ('r+'), writing new content, and truncating it to remove old content.

main.py

</>
Copy
# Open file in read-write mode ('r+')
with open("example.txt", "r+") as file:
    file.write("File overwritten using truncate method.")
    file.truncate()

print("File overwritten successfully.")

Explanation:

  1. open("example.txt", "r+") opens the file in read-write mode.
  2. write() overwrites part of the existing content.
  3. truncate() removes any remaining old content.

Output:

example.txt with updated content:

Conclusion

In this tutorial, we have covered multiple ways to overwrite a file:

  1. 'w' Mode: Completely replaces file content.
  2. pathlib.Path.write_text(): Simplifies file writing.
  3. 'r+' Mode with truncate(): Overwrites while keeping file open.