Python

Overwrite a file in Python

The term “file” refers to a named location on a disk that stores data. Python has various functions and methods to work with files. “Overwriting” a file means changing its data with updated information, as per the requirements which is essential while dealing with records. Throughout this article, we will explore several ways to overwrite a file in Python.

The below methods are available to overwrite a Python file:

Before overwriting a file, let’s take a look at the file that is going to be overwritten in this blog:

Method 1: Overwriting a File Using “write()” Method

In Python, to overwrite a file the “write()” method is utilized after opening the file in write mode. This method replaces the existing content with the new data.

Example

Here’s the code:

file = open(r'C:\Users\p\Documents\program\filename.txt', "w")
file.write("Python Guide")
file.write("\nThis text will overwrite the previous one.")
file.close()

 

In the above code, the “write()” method overwrites the text file named “filename.txt” content with the new string values. The newline character “\n” is used in between the strings to move the cursor to a new line.

Output

The specified file has been successfully overwritten.

Method 2: Overwriting a File Using “truncate()” Method

The “truncate()” method can also be utilized to overwrite a file. It removes all the content after a specified position, including that position. Here’s how to use it:

Example

The below code is used to overwrite the file:

file = open(r'C:\Users\p\Documents\program\filename.txt', "r+")
file.truncate(0)
file.write("This text will overwrite the previous one.")
file.close()

 

The above code first opens the file in read-write (“r+”) mode and then uses the “truncate()” method to remove all the existing content. Finally, the “write()” method writes the new specified data to the file.

Output

The specified file has been overwritten accordingly.

Method 3: Overwriting a File Using Mode “w”

The mode “w” is used to overwrite a file by writing to a file by modifying the existing file content.

Example

Here is an example code:

with open(r'C:\Users\p\Documents\program\filename.txt', "w") as file:
    file.write("This text will overwrite the previous one.")

 

In the above code snippet, the discussed file “filename.txt” is opened in write mode and the stated new data is written to it. The added “with” statement is used to automatically close the file.

Output

The file has been successfully overwritten in the above outcome.

Method 4: Overwriting a File Utilizing “shutil” Module

The “shutil” module delivers a high-level interface for manipulating files and directories. The “copyfile()” method of this module is also used to overwrite a file. This method copies the contents of the original file to the destination file and overwrites it if it already exists.

The file and the content that is going to be copied are shown below:

Example

The below code copies the content of one file and overwrites it to another:

import shutil
shutil.copyfile("newfile.txt", "filename.txt")

 

This code imports the “shutil” module and copies the contents of “newfile.txt” to “filename.txt” and overwrites it if the content already exists.

Output

In the output snippet, the specified file has been successfully overwritten.

Method 5: Overwriting a File Using “os” Module

The “os” module can be utilized to interact with the operating system. The “remove()” method of this module is used to delete the existing file and then create a new file with the same name to overwrite it.

Example

Let’s overview the following code:

import os
os.remove(r'C:\Users\p\Documents\program\filename.txt')
with open("filename.txt", "w") as file:
    file.write("This text will overwrite the previous one.")

 

The above code block removes the existing “filename.txt” and then creates a new file with the same name and writes the new data to it.

Output

As a result of the above code, the overwriting file has been completed.

Method 6: Overwriting a File Using “pathlib” Module

The “pathlib” module provides an object-oriented way to interact with the file system. The module’s “write_text()” method is used to write the new data to a file and overwrite the existing content.

Example

Let’s go through the following example code:

from pathlib import Path
file = Path(r'C:\Users\p\Documents\program\filename.txt')
file.write_text("Overwrite the Text File")

 

This code uses the “Path()” function to create a Path object and then uses the “write_text()” method to write the new data to the file, thereby overwriting the existing content.

Output

The above output verified that the particular file has been overwritten with new data.

Conclusion

Python has several methods for overwriting files such as the “write()” method, “truncate()” method, mode “w”, “shutil” module, “os” module, or the “pathlib” module. These methods are explained in this blog post using appropriate examples to overwrite a file in Python.

About the author

Talha Saif Malik

Talha is a contributor at Linux Hint with a vision to bring value and do useful things for the world. He loves to read, write and speak about Linux, Data, Computers and Technology.