0
number_of_lines = len(open("database.txt").readlines(  ))

f = open("database.txt" , "r+")

newpassword = "NEW"
for loop in range(number_of_lines):
   line = f.readline()
   data = line.split(",")
    if data[1] == "bye":
       data[1] = newpassword
f.close()

I don't why this code doesn't replace the string "bye" which must be in the second line of the file with newpassword.

username,password,Recovery1,Answer1,Recovery2,Answer2,Recovery3,Answer3,Recovery4,Answer4,Recovery5,Answe r5,o,o,o,o,o,o,o,o,o,o,
happy,**bye**,o,o,o,o,o,o,o,o,o,o,
bye,happy,o,o,o,o,o,o,o,o,o,o,

username,password,Recovery1,Answer1,Recovery2,Answer2,Recovery3,Answer3,Recovery4,Answer4,Recovery5,Answer5,o,o,o,o,o,o,o,o,o,o,
happy,**Hi**,o,o,o,o,o,o,o,o,o,o,
bye,happy,o,o,o,o,o,o,o,o,o,o,

Could you please write out the correct version, Thank you in advance

Gabio
  • 9,126
  • 3
  • 12
  • 32
Daniel
  • 63
  • 5

1 Answers1

0

You are changing data variable but you don't write it back to the file.

Try:

# read file data as list of lines
with open("database.txt", "r") as fr:
    lines = fr.readlines()

newpassword = "NEW"
with open("database.txt", "w") as fw:    
    for line in lines:
        data = line.split(",")
        if data[1] == "bye":
            data[1] = newpassword
        # write the data back to the file (joined by commas)
        fw.write(",".join(data))
Gabio
  • 9,126
  • 3
  • 12
  • 32
  • Beautifully done, Thank you very much. I was attempting this for over 10 days. Finally got there. @Gabip – Daniel May 11 '20 at 09:05