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