Replacing multiple words in a file using file open and write function. | Python Language Forum
H
Heena Goyal Posted on 18/11/2023
Problem: A file contains some text where in few words, you need to write a program to replace a list of those words by ###### by updating the same file.

Code:
words=['brainless', 'mindless', 'dull']

with open('sampleDonkey.txt') as f:
    content=f.read()
    print(content)
print()

for word in words:
    newcontent=content.replace(word, '######')
    with open('sampleDonkey.txt','w') as f:
            f.write(newcontent)

I have used the same code for replacng a single word in the same file and its working fine, the only difference in the code is list, here, it only replaces the last word i.e. dull. 

What mistake am I maing in this code?

The file that needs to be updated is enclosed.

Y
Yogesh Chawla Replied on 19/11/2023

We didn't put the code in right order.

Please check this:

words=['brainless', 'mindless', 'dull']

# creating a variable and storing the text that we want to add
replace_text = "#####"

# Opening our text file in read only
# mode using the open() function
with open(r'sampleDonkey.txt', 'r') as file:
    # Reading the content of the file
    # using the read() function and storing
    # them in a new variable
    data = file.read()

    # Searching and replacing the text
    # using the replace() function
    for word in words:
        data = data.replace(word, replace_text)

# Opening our text file in write only
# mode to write the replaced content
with open(r'sampleDonkey.txt', 'w') as file:
    # Writing the replaced data in our
    # text file
    file.write(data)

# Printing Text replaced
print("Text replaced")


H
Heena Goyal Replied on 29/11/2023

Couldn't find what this "r" in the below syntax is for anywhere? Why do we use this?

with open(r'sampleDonkey.txt', 'w') as file:


Y
Yogesh Chawla Replied on 29/11/2023

r is placed before filename to prevent the characters in filename string to be treated as special character. 
For example, if there is \temp in the file address, then \t is treated as the tab character and error is 
raised of invalid address. The r makes the string raw, that is, it tells that the string is without any special characters. 
The r can be ignored if the file is in same directory and address is not being placed. 
 
# Open function to open the file "MyFile1.txt" (same directory) in read mode and store its reference in the variable file1  
file1 = open("MyFile.txt", "r") 
 
#and "MyFile2.txt" in D:\Text in file2 
file2 = open(r"D:\Text\MyFile2.txt", "r")
 
We can ignore starting r in our script also since the file is present in same location as the script