In the world of programming and data manipulation, there often arises a need to find and replace specific words or phrases within a text file. Whether it’s correcting typos, updating terminology, or making consistent changes across a large dataset, knowing how to write a script for find and replace tasks is an invaluable skill. In this article, we will explore the step-by-step process of writing a Python script to find the word “UNIX” in ‘file1.txt’ and replace it with “Linux.” We’ll provide clear examples and output to help you understand and implement this task effectively.
Prerequisites:
Before we dive into writing the script, make sure you have the following prerequisites in place:
- Python installed on your system.
- A text file named ‘file1.txt’ containing the text where you want to perform the find and replace operation.
Writing the Python Script:
Let’s create a Python script that finds and replaces “UNIX” with “Linux” in ‘file1.txt’. We’ll use the built-in open()
function for file manipulation and Python’s powerful string functions.
# Import the necessary libraries
import fileinput
# Define the file to be edited
file_name = 'file1.txt'
# Define the word to be found and replaced
old_word = 'UNIX'
new_word = 'Linux'
# Perform find and replace
with fileinput.FileInput(file_name, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(old_word, new_word), end='')
Explanation:
- We import the
fileinput
module to facilitate file manipulation. file_name
is set to ‘file1.txt’, the file where we want to perform the find and replace operation.old_word
is the word we want to find (‘UNIX’), andnew_word
is what we want to replace it with (‘Linux’).- Using a
with
statement, we open ‘file1.txt’ for both reading and writing (inplace=True
) while creating a backup with a ‘.bak’ extension. - We iterate through each line in the file and use the
replace()
method to replace instances of ‘UNIX’ with ‘Linux’. - The
end=''
argument in theprint()
function ensures that the output is written back to ‘file1.txt’.
Executing the Script:
To execute the script, follow these steps:
- Ensure the ‘file1.txt’ file exists and contains text with instances of ‘UNIX’.
- Save the Python script with a .py extension (e.g.,
find_replace.py
). - Open your terminal or command prompt and navigate to the directory containing both the script and ‘file1.txt’.
- Run the script by executing
python find_replace.py
.
Output:
Upon running the script, you’ll find that all instances of ‘UNIX’ in ‘file1.txt’ have been replaced with ‘Linux.’ You can verify this by opening ‘file1.txt’ and checking the content.
Other urls to refer