文件中的变量数据 [1] 没有改变?

Variable data[1] in file not changing?

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()

我不明白为什么这段代码没有用 newpassword 替换必须位于文件第二行的字符串 "bye"。

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,

能否请你写出正确的版本, 提前谢谢你

您正在更改 data 变量,但没有将其写回文件。

尝试:

# 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))