Friday 8 March 2024

Python program to replace given words from a text file.

Python - Replace Word Program

Following Python program will replace a given word from a text file.

Example: Assume that we have a students.txt file with a following content in it:

This is a java programming class.
We will develop an Insurance Calculator using java.
Let's explore java syntax during today's lab.

Following program will replace java with python in the "students.txt" file.

# Python program to replace given words from a text file.

old_word = 'python'
new_word = 'java'

with open("students.txt", 'r') as file:
    contents = file.read()
    contents = contents.replace(old_word, new_word)

with open("students.txt", 'w') as file:
    file.write(contents)

print(f'Replaced "{old_word}" with "{new_word}" in students.txt.

Sample output:

Replaced "java" with "python" in students.txt.


Content of a students.txt file after execution of a program:

This is a python programming class.
We will develop an Insurance Calculator using python.
Let's explore python syntax during today's lab.

No comments:

Post a Comment