Python:在特定行下替换字符串

问题描述 投票:0回答:1

很抱歉,我通常会尽量避免无用的问题,但是我已经四处寻找了我的问题的答案。

基本上,我在.txt文件中有这段代码:

<item name="Find_this_keyword">
ente<value type="vector">[-0.1 0.2 0.3 1.4]
</item>

此行在与此相似的一千行之内,只是该关键字有所不同。因此,基本上我想让python在带有该关键字的行下更改行。我需要将向量中的4个数字更改为其他4个数字。

您有任何线索吗?

感谢您的时间

python str-replace
1个回答
0
投票

您可以尝试这样的事情。

code.txt

new_vals = [1, 2, 3, 4]
f1 = open('code.txt', 'r')
f2 = open('code_out.txt', 'w')
for line in f1:
    newline = line
    if 'ente<value type="vector">' in line: 
         newline = 'ente<value type="vector">' + f'[{new_vals[0]} {new_vals[1]} {new_vals[2]} {new_vals[3]}]'
    f2.write(newline)

f1.close()
f2.close()
© www.soinside.com 2019 - 2024. All rights reserved.