-1

I am creating an application with Pyqt5 (QT). The application do the Password Manager tasks.

I have a text file that names and passwords stored in it (encrypted).

One section of app has a tool that user can change the password from entering the name. (If you don't understand look at the picture.)

screenshot

My text file is like this :

newname1|password1
newname2|password2
...

As you noticed, after "|" is the password. How can I find newname2 and just replace the password section from new password field, or remove the line and replace with a new one (for example: newname2|newpassword)?

Also I have to say that I know how to fetch data from inputs, I just want to know how to do it in python code.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • I removed `PyQt` tag since the problem is about reading the data from the text file, and it doesn't actually have anything to do with `PyQt`. You can still edit the answer and add that tag if you really think that is going to help you. – ThePyGuy Jul 21 '21 at 10:47
  • 1
    @ThePyGuy Ok thanks, but can't you help me? – Mahdi Yaghoubi Jul 21 '21 at 10:56

2 Answers2

1

Something like this should work:

out = open('file.txt', 'r').readlines()
name, newPass = 'newname2', 'NewPassword2'
for idx,line in enumerate(out):
    if line.startswith(name+'|'):
        out[idx] = f'{name}|{newPass}'
        fBuffer = open('file.txt', 'w')
        fBuffer.writelines(out)
        break
else:
    print('User Name not found')
    

You can take the name, and newPass from PyQt UI's lineEdit, read the file which has the name and the passwords stored, then iterate through these lines and check if newname2| is there in the file, if so, update the list. Then write back to the file, and exit the loop immediately.

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
0
string = '''
a|b
c|d
'''

username = 'a'
new_password = '123'


import re

new_string = re.sub(f'(?<=^{username}\|).*', new_password , string,  flags=re.M)

print(new_string) # This string can be written back to the file.

Note: Not efficient but works.

Darcy
  • 160
  • 1
  • 9