简体   繁体   English

使用python将列表中的元素搜索并替换为字符串,并将其替换为新文件

[英]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). 我一直在尝试编写一个脚本来读取file1的内容,并用在程序较早部分创建的列表元素(迭代使用for循环)替换“特定字符串”(兔子),并将其内容写入一个新文件(file2)。

In the below code "new_list" is a list created from the contents of file1. 在下面的代码“ new_list”中是一个从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). 所以我在这里面临的问题是因为我正在使用for循环,因此file1的所有内容多次写入file2(列表中的元素数)。 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. 但是我有兴趣仅用列表元素替换“兔子”字符串/行(反复不触碰其他行/字符串)并将其写入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 您可以使用str.join写入列表的内容,replace只会更改rabbit出现的行,因此绝对不需要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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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