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

2024-09-29 23:28:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个属性文件,必须通过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新手


Tags: 文件编辑密码属性adminpwdlinesome
1条回答
网友
1楼 · 发布于 2024-09-29 23:28:04

您可以做的是,首先打开文件,然后将所有行读入一个列表content,然后从每个行中删除\n。从这里你可以在这个列表中搜索你的target,其中包含单词或一些独特的短语,为此我们使用了password。不,我们可以将它设置为target,同时在=处拆分它,还可以存储target_idx。从这里我们只需改变target的第二个索引,我们.split('='),然后.join()把它们放在一起。现在我们可以将新行phrase分配给contenttarget_idx来替换旧的target。在打开text.txt备份并使用'\n'.join(content)编写新的content之后

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

相关问题 更多 >

    热门问题