Finding a specific line in a file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Finding a specific line in a file (/thread-20938.html) |
Finding a specific line in a file - Vqlk - Sep-07-2019 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? RE: Finding a specific line in a file - Axel_Erfurt - Sep-07-2019 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)
RE: Finding a specific line in a file - Vqlk - Sep-07-2019 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 RE: Finding a specific line in a file - Axel_Erfurt - Sep-07-2019 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 |