-3

I have a properties file and have to edit it through python. I need to edit the line jmx.admin.pwd=SomeRandomPassword and replace the random password with my own password. 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.

bereal
  • 32,519
  • 6
  • 58
  • 104
  • 4
    Can you update your question with what you have tried in python so far ? show us your effort, and where it goes wrong. Give as much informaiton about your code as possible. Also update the question with the actual output of your code. – Edwin van Mierlo Oct 08 '18 at 09:53
  • 1
    General Algo...iterate your text file line by line and match "min.pop.password". When the condition matches replace it with the string you want – Rahul Agarwal Oct 08 '18 at 09:54
  • So you should show what have you tried so far. This previous questions may be helpful to you: https://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file-using-python – Ashutosh Bharti Oct 08 '18 at 09:58

1 Answers1

0

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. 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. No we can set that to target while splitting it at the =, and also store the target_idx. From here we just alter the second index of target that we .split('=') and then .join() that back together. Now we can assign our new line phrase to the target_idx of content replacing the old target. After we can open our text.txt back up and write the new content using '\n'.join(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
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20