简体   繁体   English

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

[英]Editing a line of text file after a word

I have a properties file and have to edit it through python.我有一个属性文件,必须通过 python 编辑它。 I need to edit the line jmx.admin.pwd=SomeRandomPassword and replace the random password with my own password.我需要编辑行jmx.admin.pwd=SomeRandomPassword并用我自己的密码替换随机密码。 I am unable to do so.我无法这样做。

The text file looks like this:文本文件如下所示:

some line
some line
some line
min.pop.password=SomeRandomNumbersWordsCharacters
some line
some line
some line

Below should be the modified output:下面应该是修改后的输出:

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

Any help is highly appreciated as I am new in Python.由于我是 Python 新手,因此非常感谢任何帮助。

What you can do is, first open the file, then read all the lines into a list content removing \\n from each as you do so.您可以做的是,首先打开文件,然后将所有行读入列表content从每个行中删除\\n From here you can search this list for your target which has the word or some unique phrase in it, for this we used password .从这里你可以搜索这个列表,您的target具有的单词或它的一些独特的词组,对于这一点,我们使用password No we can set that to target while splitting it at the = , and also store the target_idx .不,我们可以将它设置为target同时在=处拆分它,并存储target_idx From here we just alter the second index of target that we .split('=') and then .join() that back together.从这里我们只需更改我们.split('=')target的第二个索引,然后将.join()重新组合在一起。 Now we can assign our new line phrase to the target_idx of content replacing the old target .现在我们可以将我们的新行phrase分配给替换旧targetcontenttarget_idx After we can open our text.txt back up and write the new content using '\\n'.join(content)在我们可以打开我们的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))

Before

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

After

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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