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
fw.write(",".join(data))