![](/img/trans.png)
[英]How to search a string(say str1) and replace it with another string(say str2) in a file using python?
[英]Python: search for a STR1 in a line and replace the whole line with STR2
我有一個文件,我需要在其中搜索STR1
並替換包含STR2
的整個行。 例如, file1
包含以下數據
Name: John
Height: 6.0
Weight: 190
Eyes: Blue
我需要在上面的文件中搜索Name
,然后將整個行替換為Name: Robert
。 我可以輕松地完成此操作
sed -i 's/.*Name.*/Name:Robert/' file1
但是如何在python中獲得相同的結果。 例如,我可以使用fileinput
將一個字符串替換為另一個字符串,如下所示
#! /usr/bin/python
import fileinput
for line in fileinput.input("file1", inplace=True):
# inside this loop the STDOUT will be redirected to the file
# the comma after each print statement is needed to avoid double line breaks
print line.replace("Name: John", "Name: Robert"),
如何修改以上代碼以替換整行,即使使用搜索條件,使用'*'
替換文件中的所有行( if "Name" in line
)
您可以使用string.find()
確定一個字符串是否在另一個字符串中。 相關的Python文檔 。
#! /usr/bin/python
import fileinput
for line in fileinput.input("file1", inplace=True):
if line.find("Name:") >= 0:
print "Name: Robert"
else:
print line[:-1]
應該正是您想要的。
def replace_basic(key_to_replace, new_value, file):
f = open(file, 'rb').readlines()
with open(file, 'wb') as out:
for line in f:
if key_to_replace in line:
out.write(new_value+'/n') #asuming that your format never changes then uncomment the next line and comment out this one.
#out.write('{}: {}'.format(key_to_replace, new_value))
continue
out.write(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.