繁体   English   中英

如何在 Python 中搜索和替换一行中的特定值

[英]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.

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