224k views
5 votes
Write a program that removes all the occurrences of a specified string from a text file. Your program should prompt the user to enter a filename and a string to be removed.

1 Answer

6 votes

Answer:

filename = input("Enter file name: ")

rm_word = input("Enter word to remove from file: ")

with open(filename, "r") as file:

mytext = file.read().strip()

replace_word = mytext.replace(rm_word, "")

print(replace_word)

Step-by-step explanation:

The python program prompt user for the file name and the string word to remove from the text. The file is opened with the 'with' keyword and the file content is read as a string and stripped of white space at the beginning and end of the string. The string's 'replace' method is used to remove the target word.

User Cuddlemeister
by
5.3k points