如何用Python Tkinter文件中的另一个字符串替换条目中的字符串

如何用Python Tkinter文件中的另一个字符串替换条目中的字符串,python,tkinter,replace,overwrite,Python,Tkinter,Replace,Overwrite,我正在尝试我有两个条目,分别是oldpassword和newpassword。用户必须以特定格式键入文件中已存在的oldpassword。如果他键入有效的oldpassword,他就可以更改密码。问题在于Python中的.replace函数。我无法将文件中的旧密码替换为新密码。代码如下: def checkpw(): oldpass = oldpasswordvar.get() newpass = newpasswordvar.get() with open('file.

我正在尝试我有两个条目,分别是
oldpassword
newpassword
。用户必须以特定格式键入文件中已存在的
oldpassword
。如果他键入有效的
oldpassword
,他就可以更改密码。问题在于Python中的
.replace
函数。我无法将文件中的旧密码替换为新密码。代码如下:

def checkpw():
    oldpass = oldpasswordvar.get()
    newpass = newpasswordvar.get()
    with open('file.txt', 'r+') as f:
        for line in f:
            list = line.split()
            pw = list[3]
            if pw == oldpass:
             f.write(line.replace(pw,newpass))


文件如下所示:

2 3 101 www
4 5 102 qpw
6 7 103 lpl
8 9 104 qpq


所以基本上

  • 我使用
    split
  • 然后我检查
    oldpass
    是否等于
    list[3]=“www”、“qpw”、“lpl”、“qpq”
  • 如果相等,我想用
    newpass
    变量替换该字符串
但它所做的只是:只需在文件末尾添加一个全新的行

它不能代替字符串。有什么想法吗?

你不能在这样的文件中间写一行修改过的密码——如果新密码比旧密码长,就没有空间了!即使长度相同,文件位置也已经超出了读取旧密码的行,因此
.write()
将覆盖其他内容。(无论如何,您的
.replace()
方法从根本上被打破了。假设有人将密码设置为
1
,然后对其进行了更改:您也要在第三个字段中替换该
1
)那么有什么办法完成此操作吗?1。阅读整个文件。2.做些改变。3.重写从另一个线程解决的整个文件问题。感谢大家的帮助!