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
  [Solved] Trying to read specific lines from a file Laplace12 7 188 10 hours ago
Last Post: Laplace12
  Extract specific sentences from text file Bubly 3 253 May-31-2021, 06:55 PM
Last Post: Larz60+
Exclamation Why there's a 'blank line' on CSV file? brunolelli 4 522 Mar-25-2021, 03:43 AM
Last Post: buran
  Printing a specific line from a JSON serpiente 4 591 Mar-14-2021, 07:27 PM
Last Post: buran
  Find specific file in an archive tester_V 8 681 Feb-13-2021, 06:13 PM
Last Post: tester_V
  Writing to file in a specific folder evapa8f 5 785 Nov-13-2020, 10:10 PM
Last Post: deanhystad
  finding element of specific field in pandas adjacency matrix amjass12 0 335 Oct-27-2020, 09:27 AM
Last Post: amjass12
  Find frequencies of an audio file at a specific time via librosa jberesford123__ 0 391 Oct-21-2020, 01:18 PM
Last Post: jberesford123__
  Extracting data based on specific patterns in a text file K11 1 658 Aug-28-2020, 09:00 AM
Last Post: Gribouillis
  Find specific subdir, open files and find specific lines that are missing from a file tester_V 8 1,121 Aug-25-2020, 01:52 AM
Last Post: tester_V

Forum Jump:

User Panel Messages

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