首页 > 解决方案 > 为什么我无法在 tkinter 中找到或输入已添加到文件的条目?

问题描述

with open("emails.txt", "a+") as emailList:
    for line in emailList:
        if str(emailEntry.get()) in line:
            print("Someone already used this e-mail")
            break;
        else:
            emailList.write("\n" + str(emailEntry.get()))

#这段代码应该检查 emails.txt 中的字符串是否与在 tkinter 中使用 Entry 小部件输入的字符串相同,如果输入的字符串与输入的程序相同,则需要打印“有人已经使用过这封电子邮件”并停止该 if 语句。如果 emails.txt 中的字符串与输入的字符串不同,则应将该字符串添加到文件中。#但我的程序每次(无论我输入什么)都不做任何事情

标签: pythonfiletkinter

解决方案


这是因为您以模式打开文件a+,该模式将文件指针放在文件末尾。因此 for 循环将立即结束,并且没有任何反应。

您需要以r+模式打开文件。下面是一个工作示例:

email = emailEntry.get().strip()
if email:
    with open('emails.txt', 'r+') as emailList:
        found = False
        for line in emailList:
            if email == line.strip():
                found = True
                break
        if found:
            print('Someone already used this e-mail')
        else:
            print('add', email, 'to file')
            emailList.write('\n'+email)


推荐阅读