Python Forum

Full Version: Finding a specific line in a file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have created a login app and have started work on a forgotten password module. I want to change the password in a txt file. The passwords will differ. The text file looks like:

username:
door
first name:
Random
last name:
person
age:
111
password:
saaS`1112
email:
[email protected]

i want to be able to change the password (not the line that says password but the one below it) line to a different string. Is this possible?
maybe something like this

text = """username:
door
first name:
Random
last name:
person
age:
111
password:
saaS`1112
email:
[email protected]"""

pw = text.partition("password:\n")[2].partition("\nemail:")[0]
newpassword = "python"
newtext = text.replace(pw, newpassword)
print(newtext)
Output:
username: door first name: Random last name: person age: 111 password: python email: [email protected]
Sorry for the confuion but that text was in a text file, I want to see if I can edit it from the python editor
You should know how to open a textfile.
change the path ( i've used /tmp/test.txt)

with open("/tmp/test.txt", 'r') as f:
    text = f.read()
    f.close()

pw = text.partition("password:\n")[2].partition("\nemail:")[0]
newpassword = "python"
newtext = text.replace(pw, newpassword)
print(newtext)

with open("/tmp/test.txt", 'w') as f:
    f.write(newtext)
    f.close