Python Forum
Finding a specific line in a file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Finding a specific line in a file
#1
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?
Reply
#2
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]
Reply
#3
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
Reply
#4
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Extracting specific file from an archive tester_V 4 423 Jan-29-2024, 06:41 PM
Last Post: tester_V
  File "<string>", line 19, in <module> error is related to what? Frankduc 9 12,389 Mar-09-2023, 07:22 AM
Last Post: LocklearSusan
  Getting last line of each line occurrence in a file tester_V 1 811 Jan-31-2023, 09:29 PM
Last Post: deanhystad
  Reading Specific Rows In a CSV File finndude 3 940 Dec-13-2022, 03:19 PM
Last Post: finndude
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,305 Sep-27-2022, 01:38 PM
Last Post: buran
  How to extract specific data from .SRC (note pad file) Shinny_Shin 2 1,224 Jul-27-2022, 12:31 PM
Last Post: Larz60+
  Print to a New Line when Appending File DaveG 0 1,189 Mar-30-2022, 04:14 AM
Last Post: DaveG
  Extracting Specific Lines from text file based on content. jokerfmj 8 2,856 Mar-28-2022, 03:38 PM
Last Post: snippsat
  Find and delete above a certain line in text file cubangt 12 3,353 Mar-18-2022, 07:49 PM
Last Post: snippsat
  CSV to Text File and write a line in newline atomxkai 4 2,611 Feb-15-2022, 08:06 PM
Last Post: atomxkai

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020