[英]How to search and replace a specific value in a line in Python
我有一個文本文件,其中包含一些值,如下所示:
matlab.file.here.we.go{1} = 50
matlab.file.here.sxd.go{1} = 50
matlab.file.here.asd.go{1} = 50
我希望代碼查找“matlab.file.here.sxd.go{1}”並將分配給它的值從 50 替換為 1。但我希望它是動態的(即,稍后我將擁有超過 20 個值改變,我不想搜索那個特定的短語)。 我是 python 的新手,所以我沒有太多信息可以在線搜索。 謝謝
我嘗試了以下
file_path = r'test\testfile.txt'
file_param = 'matlab.file.here.we.go{1}'
changing = 'matlab.file.here.we.go{1} = 1'
with open(file_path, 'r') as f:
content = f.readlines()
content = content.replace(file_param , changing)
with open(file_path, 'w') as f:
f.write(content)
但它沒有達到我想要的
您可以拆分等號。 您可以同時讀取和寫入文件。
import os
file_path = r'test\testfile.txt'
file_path_temp = r'test\testfile.txt.TEMP'
new_value = 50
changing = 'matlab.file.here.we.go{1} = 1'
with open(file_path, 'r') as rf, open(file_path_temp, 'w') as wf:
for line in rf:
if changing in line:
temp = line.split(' = ')
temp[1] = new_value
line = ' = '.join(temp)
wf.write(line)
os.remove(file_path)
os.rename(file_path_temp, file_path)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.