How Can We Help?
Introduction
Python allows us to use quite a large number of ways actually to replace the texts in a file. This includes both in-built functions as well as other modules and libraries. Programmers often need to deal with many files.
In this article, we will understand how to replace text in files in python.
Replace The Complete File With a String
Python allows us to replace the whole document with any string we define. Python also allows us to use quite a large number of methods to perform this operation. The most basic method is by using the open function. This is an in-built function of python. But the function will only open the text file for us. We also need to specify the format in which we need to import the file. For example, if we want to perform only a read operation, then we need to pass the argument “r”; for a write operation, we need to pass the argument “w” etc.
Python supports the following file-handling operations:
- r: This stands for reading operation
- w: This stands for the write operation.
- a: We use this for append operation.
- w+: We use it for creating files reading, and writing operations.
- r+: We use it for reading and writing operations without creating new text files.
- a+: This is used for reading, writing, and appending operations by creating a new file.
Open Function
Syntax:
open(<name of the text file in string>,<operations to be performed>)
Parameters:
Name of the text file
The operation to be performed.
Return value:
Null. It only helps to access the text files
Next, we need to use the truncate function to truncate the texts. If we want to replace the whole text, we must pass the value 0 as its argument.
Syntax:
<file name>.truncate(<number of characters up to which we need the truncate operation to perform>)
Parameters:
number of characters up to which we need the truncate operation to perform
Return value:
Null. It will truncate the texts.
Note that closing the file after file operation is good practice.
Before we code, we need to make the text file. Follow these steps.:
- First, create a text file in the same directory where you will code the python program. Name it “example.txt”.
- Name your python file index.js. You can choose any other name for both the python as well as the text file.
- Now type the following lines in the text file :
Hello, this is the first line of the file.
Hello, this is the second line of the file.
Hello, this is the Third line of the file.
Your file structure should look like this. Note that you are free to use any other code editor. Here we are using the vs. code with the jellyfish theme.
Now we can code in the index.py file.
Example (1)
# Define the text with which we need to replace the text with
string = "REPLACED TEXT"
# Open the file using read and write mode
file = open("example.txt", "r+")
# Truncate the texts within the file
file.truncate(0)
# Write the text into the file
file.write(string)
# Close the file
file.close()
# Check if everything is done successfully.
print("Hi there, your text has been successfully replaced")
Output:
Hi there, your text has been successfully replaced
Explanation:
- First, we have defined the string which we want to replace the whole file. We stored the text in the variable named string.
- Next, we opened the file named example.txt with the read and write mode by specifying the parameter “r+”. Next, we used the truncate function and passed the value 0 to remove all the text from the file.
- Now we used the write function to write the string into the file. Next, we closed the file using the close function.
- Finally, we printed the following texts using the print function:
print(“Hi there, your text has been successfully replaced”)
- Now run the python file. Immediately after, it opens the example.txt file now. You will find that the text of the file is changed with the following string:
REPLACED TEXT
Replacing The String Within The Same File Using Replace Function
Replace function is again a built-in function of python, allowing users to replace the texts of any file with user-specified text.
Syntax:
file.replace(<string to be replaced>, <string with which we need to replace>)
Return value:
Null. The function only performs the replace operation.
Before proceeding with the code, follow the following steps:
- Create a python file named “index.py”.
- Next, create another file named “input.txt”.Write the following lines of text into the text file:
Hello, this is the first line.
Hello, this is the second line
Example (2)
# Read the input file in read mode
input_file = open("input.txt", "rt")
# Read the input file
texts = input_file.read()
# Replace the specified string
texts = texts.replace('Hello', 'HELLO PYTHON USER')
# Close the input file
input_file.close()
#Open the file again using write operation
input_file = open("input.txt", "wt")
# Overrite the input file with the new texts
input_file.write(texts)
# Close the file
input_file.close()
Output:
Explanation:
- First, open the file input.txt using the open function of python. We opened the file using rt mode. Note that this is important to open in reading mode only.
- Next, we read the text file using the read function of python. We replaced the string “Hello” with the string “HELLP PYTHON USER”.
- We closed the file. Next, we opened the file again but with the write mode this time. We have written the resulting texts into the file using the write function of python. We have passed the parameter texts to this function which stores the replaced texts.
Replacing Specific Texts and Writing Onto Another File
Python also allows one to read a particular file and replace the text by writing it into another file.
We can use the open function of python to read the files and write a function to write into another file.
Syntax:
<file name>.write(<texts to write>)
Return value:
Null. The function performs a write operation.
Before we proceed with the codes, follow the following steps:
- Create two files named “initial.txt” and “new.txt” in the same directory where you will place your python file.
- Next, create a python file named “index.py”.
- Write the following texts in the “new.txt” file:
Hello, this is the first line.
After following all the steps, write the following codes in the index.py file:
Example (3)
# Read the initial file
input_file = open("initial.txt", "rt")
# Open the output file
out_file = open("new.txt", "wt")
# Iterate through the lines of the first file
for line in input_file:
# Write onto the output file.
out_file.write(line.replace('Hello', 'HELLO'))
# Close both files.
input_file.close()
out_file.close()
Output:
You will observe that the text is written into the new.txt file.
Explanation:
- First, we opened the initial.txt and the new.txt file. We needed to read the initial.txt file, so we used the rt mode. On the other hand, we need to perform a write operation for the new.txt file, so we used the wt method.
- Next, we iterated through the input file with the help of the for a loop. We replaced the string “Hello” with “HELLO” and wrote the string into the output file, which is the new.txt file using the write function.
- We closed both functions using the following lines of codes:
input_file.close()
out_file.close()
Using The os Module
Another method we can adopt to achieve a similar final achievement is using the os module. The os module helps to deal with the operating system.
We can perform the following process to replace the texts of a file:
- First, import the module and define the text you need to replace the file.
- Next, open the input file which should be replaced. Open another file and write the replaced text.
- Remove the input file and rename the second file with the initial input file. Although the output is the same, we are not precisely replacing the string. We are writing the updated text into another file, deleting the parent file, and renaming the updated file to the parent file and slightly cheating!
Before we code, follows the followings:
- Create a text file named “input.txt” and “index.py’ in the same directory.
- Now write the following lines into the input.txt file:
Hello, this is the first line.
Hello, this is the second line.
Example (4)
# Import, the os module of python
import os
# Define the text with which the file is to be replaced
replced_text = "Hello this is the replaced text."
# Read the input file
input_file = open("input.txt", "r+")
# Create and open a new file named "new.txt"
with open("new.txt", "w") as file:
# Write into the new file
file.write(replced_text)
# Close the newly created file
file.close()
# Remove the input file "input.txt"
os.remove("input.txt")
# Rename the "new.txt" file to "input.txt"
os.rename("new.txt", "input.txt")
print("input replaced")
Output:
input replaced
Explanation:
- We first imported the os module in the code using the import statement of python. Next, we defined the text with which we needed to replace the text of the input file.
- We opened the input.txt file using the open function of python and in” r+” mode.
- Next, we used the following statement to create a file named new.txt and write into the file:
- with open(“new.txt”, “w”) as file:
# Write into the new file
file.write(replced_text)
# Close the newly created file
file.close()
- We have written into the new.txt file using the write function. We also closed the file after all the operations.
- Next, we removed the input.txt file, which was our input file, using the remove function of the os module.
- We renamed the “new.txt” file with the “input.txt” file.
How to Replace Multiple Strings Within a file in Python
Python not only allows us to replace single strings but also allows us to change multiple strings. We can use our logic to perform the same with the help of all the methods we discussed earlier. This section will describe a recommended way to achieve the same. Readers are, however, free to choose any method they want.
We can adopt the following method to replace multiple strings in Python:
- First, open the text file in reading mode. Next, define all the strings you need to replace in data types like lists, tuples, etc. Along with it, define the sequence of new strings you want to replace.
- Create an empty string, say “lines”.
- Next, iterate through the input file and zip the two lists. Use the replace function of Python to replace the old strings with the new strings. Concatenate the new line with the lines variable.
Now close the input file and again open the text file. But this time, open with write mode. Now write the lines variable into the file using the write function and close the text file.
Example (5)
# Read the input file
input_file = open('input.txt', 'r')
# Define all the texts to change in the file
old_str = ["Hello", "file"]
# Define all the new texts that is to be added
new_str = ["HELLO", "FILE"]
# Define an empty string
lines = ""
# Iterate through the input files
for line in input_file:
# zip the two lists to have a pair
for old, new in zip(old_str, new_str):
# Replace the old string with the new one
line = line.replace(old, new)
# Concatenate the new line
lines = lines+line
# Close the input file
input_file.close()
# Again open the input file but with write mode
output_file = open('input.txt', 'w')
# Now write all the lines to it using the write function
output_file.write(lines)
# Close the file.
output_file.close()
Output:
Conclusion:
In this article, we learned how to replace the strings of a file using different methods. We used open function, os modules of python to perform the same. Python offers many functions, like reading, readlines, write, etc., to perform file handling. Also, we need to specify the mode in which we open the file in python.
We have discussed most of the essential functions and techniques associated with the topic. However, we strongly recommend the users go through the python documentation to have more understanding of the topics. Additionally, we strongly encourage the readers to post your queries in our ORAASK forum.
Additionally, we recommend that the readers try to practice the operations on their own using a combination of different methods to understand all the operations better.