Python

Overwrite a file in Python

Python provides various built-in functions for File manipulation by using a file object, so there is no need to import modules externally. Handling a file is the most vital factor in an operating system. This article will demonstrate some methods to overwrite files in python.

We will look into all methods. Implement some action and change it and at that time overwrite it with entirely new data. Let’s go-ahead to implement and execute a valid example. These methods are following:

  1. Open() method
  2. Truncate() method
  3. Replace() method
  4. Os.remove() method
  5. Shutil.Move() method

Example 1: Using the open() method to overwrite a file.

The open() method takes two parameters as an argument: the path of the file and the mode either it can be a read mode ‘r’ or a write mode ‘w’. To overwrite a file, to write new content into a file, we have to open our file in “w” mode, which is the write mode. It will delete the existing content from a file first; then, we can write new content and save it.

We have a new file with the name “myFile.txt”. Firstly, we will open a file in the open() method that takes a file name or path and adds some content to the file with the mode ‘a’ that is append mode; it will append content in the file.

For writing some content in the file, we have to use myFile.write() method. After that, we open and read the file by using ‘r’ mode. We can fetch the file content by the print statement.

myFile = open("myFile1.txt", "a")

myFile.write("This is my file having some content!")

myFile.close()

myFile = open("myFile1.txt", "r")

print(myFile.read())

This is the output of appending and reading the content a file has. Below the screenshot, you can see the content of a file.

Now we are using ‘w’ mode to overwrite existing content with the new one and the open a file with open() method along with the ‘r’ mode to read the new content in the file.

myFile = open("myFile1.txt", "w")

myFile.write("This is my file having some new content!.We have deleted the previous one ")

myFile.close()

myFile = open("myFile1.txt", "r")

print(myFile.read())

Here is the output of the new content in the file ‘myFile.txt’.

Example 2: Using the truncate() method to overwrite a file.

This truncate() method allows us to remove the data of the file. For this, we have to use seek() function. This method that sets the pointer at the start of the file by default is set to zero. Using this function, we can write new content and truncate the older one.

Now we have another example of how the truncate() method truncated the content in the existing file. We open the file ‘myFile1.txt’ in the write mode, call the function seek() set at pointer zero, and write new content in write().

Then to read a file with new content, we have to use ‘r’ and Display the print() that stores myFile2.read() through which we can read the new content.

myFile2= open("myFile1.txt", "w")

myFile2.seek(0)

myFile2.write("New content by using truncate() method")

myFile2.truncate()

myFile2= open("myFile1.txt", "r")

print(myFile2.read())

The output displays the new content on a console screen below.

Example 3: Using replace() method

Next is the replace() method, which will overwrite the given string by replacing it with a different string. We can write the new content in the existing file by opening it in write ‘w’ mode, changing the string content, and automatically removing the previous content in the file.

Below is the example that will replace a string ‘content’ into ‘information’ by new_content.replace() function into a ‘myFile3’ variable that we will read in the print function.

myFile = open("myFile1.txt", "r")

new_content = myFile.read()

new_content=new_content.replace('content','information')

myFile.close()

myFile3=open('myFile1.txt','w')

myFile3.write(new_content)

myFile3= open("myFile1.txt", "r")

print(myFile3.read())

The output of the replace string is shown below:

Example 4: Using the os.remove() method to overwrite a file.

Here is the method to overwrite a file; if we want to create a new file. We have to remove a previous file for this. We have to call a method os.remove(). It will remove or delete a file path.

For this first, we have to check whether a file exists or it’s a valid file through is.Path.Exist() function because OsError occurs if the file does not exist or it may be an invalid or inaccessible file name or path.

Let’s run the example code of how the os.remove() method works. First, we need to import the os module then we have a conditional statement to check whether a file exists or not. In this case, we have the existing file, so os.remove() will delete a file text in it. By File_new.write(), we can write a new content. Then read mode will show us the new content.

import os

if (os.path.exists("pythonFile.txt")):

os.remove("pythonFile.txt")

else:

print("File Not Found")

file_new = open("pythonFile.txt", "w")

file_new.write('My new content about os.rmeove() method')

file_new.close()

file_new =open("File_New.txt", "r")

print(file_new.read())

As you can see, the previous content was removed, and we have an output of newly created content.

Example 5: Using shutil.move() method to overwrite a file.

If we want to move a file to a directory where the existing file with the same name is present, we will have a shutil. The move() method can be achieved by importing the shutil module.

The shutil.move() overwrites the file destination with a new source file. For thi,s we have passed ‘src’ and ‘dst’ as an argument in the shutil.move() method as shutil. move(src,dst). This will move a source file “src” to a destination “dst”. The return value from this method is a string that represents the path of a file that is newly created.

To move a file into a new directory, we have to import the shutil library. After that, we have assigned a source path in ‘my_source’ and a destination path to ‘my_destination’. The os.path.basename() will get the filename and through os.path.join(), it will be the destination path filename . The method shutil.move() will take my_source and dest_path as arguments and move the files.

import shutil

import os

 

my_source = "c:\\users\\Hp\\Desktop\\images\\ship.jpg"

my_destination = "F:\\Desktop data\\python_article"

my_filename = os.path.basename(my_source)

dest_path = os.path.join(my_destination,my_filename)

shutil.move(my_source, dest_path)

print('Current Source to move',my_source)

print("New Destination path:", dest_path)

As you can see, the current source path file ‘ship.jpg’ moved to a new destination path. Displaying the output below:

Conclusion

We have gone through various methods for overwriting a file in python with the implementation of simple examples that are easy to understand. This article will give your hands in handling file overwriting in an efficient and proficient way.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content