简体   繁体   中英

search & replace elements of a list into a string iteratively into a new file using python

I have been trying to write a script to read the contents of file1 & replace a "specific string" (rabbit) with elements of a list (iteratively using for loop) that I have created in earlier part of the program and write the contents to a new file (file2).

In the below code "new_list" is a list created from the contents of file1. so the problem I am facing here is as I am using for loop, all the contents of file1 are written to file2 multiple times (# of elements in the list). But I am interested in just replacing "rabbit" string/line with list elements (iteratively with out touching other lines/strings) & write it to a newfile/file2. Could anyone please help me here to find the right solution?

file1  = open(filename, 'r')
file2 = open('newfile', 'r+')
for line in file1:
 for s in new_list:
       animal = line.replace('rabbit', s )
       file2.write(animal)
file1.close()
file2.close()

You can use str.join to write the contents of the list, replace will only change that lines the rabbit appears in so there is absolutely no need for a try/except

 with open(filename, 'r') as file1,open('newfile', 'w') as file2:
    for line in file1:
       line = line.replace('rabbit', " ".join(new_list) )
       file2.write(line)

Its because of your loops order , change it to :

for s in new_list:
   for line in file1:
     try:  
       line = line.replace('rabbit', s )
       file2.write(line)
     except:
       continue 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM