Python 在单词后编辑一行文本文件

Python 在单词后编辑一行文本文件,python,text,replace,line,edit,Python,Text,Replace,Line,Edit,我有一个属性文件,必须通过python对其进行编辑。我需要编辑行jmx.admin.pwd=SomeRandomPassword,并用我自己的密码替换随机密码。我不能这样做 文本文件如下所示: some line some line some line min.pop.password=SomeRandomNumbersWordsCharacters some line some line some line 以下是修改后的输出: some line some line some line m

我有一个属性文件,必须通过python对其进行编辑。我需要编辑行
jmx.admin.pwd=SomeRandomPassword
,并用我自己的密码替换随机密码。我不能这样做

文本文件如下所示:

some line
some line
some line
min.pop.password=SomeRandomNumbersWordsCharacters
some line
some line
some line
以下是修改后的输出:

some line
some line
some line
min.pop.password=My_Password
some line
some line
some line

非常感谢您的帮助,因为我是Python新手。

您可以做的是,首先打开文件,然后将所有行读入列表
内容
删除
\n
。从这里,您可以在此列表中搜索您的
目标
,其中包含单词或某些独特短语,为此,我们使用了
密码
。不,我们可以将其设置为
目标
,同时在
=
处拆分,还可以存储
目标_idx
。从这里开始,我们只需修改
target
的第二个索引,即
.split('=')
,然后将其重新组合在一起。现在,我们可以将我们的新行
短语
分配给
内容的
目标_idx
,替换旧的
目标
。在我们可以打开
text.txt
备份并使用
'\n>编写新的
内容之后。加入(内容)

以前

之后


您能用迄今为止在python中尝试的内容更新您的问题吗?向我们展示你的努力,以及哪里出了问题。尽可能多地提供有关代码的信息。同时用你的代码的实际输出更新问题。通用算法…逐行迭代你的文本文件并匹配“min.pop.password”。当条件匹配时,将其替换为您想要的字符串,以便显示到目前为止您尝试了什么。上述问题可能对您有所帮助:
with open('text.txt') as f:
    content = [line.strip() for line in f]

for i in content:
    if 'password' in i:
        target = i.split('=')
        target_idx = content.index(i)

target[-1] = 'My_Password'
mod = '='.join(target)

content[target_idx] = mod

with open('text1.txt', 'w') as f:
    f.write('\n'.join(content))
chrx@chrx:~/python/stackoverflow/10.3$ cat text.txt 
some line
some line
some line
min.pop.password=SomeRandomNumbersWordsCharacters
some line
some line
some line
chrx@chrx:~/python/stackoverflow/10.3$ cat text.txt 
some line
some line
some line
min.pop.password=My_Password
some line
some line
some line