文件中的可变数据[1]不变吗?

问题描述 投票:0回答:1
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,

请您写下正确的版本,预先谢谢你

python file append
1个回答
0
投票

您正在更改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))
© www.soinside.com 2019 - 2024. All rights reserved.