为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我在 tkinter 中找不到或输入添加到文件中的条目?

为什么我在 tkinter 中找不到或输入添加到文件中的条目?

精慕HU 2023-08-15 16:42:40
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 中的字符串与输入的字符串不同,则应将该字符串添加到文件中。#但是我的程序每次(无论我输入什么)都不做任何事情
查看完整描述

1 回答

?
回首忆惘然

TA贡献1847条经验 获得超11个赞

这是因为您以模式打开文件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)


查看完整回答
反对 回复 2023-08-15
  • 1 回答
  • 0 关注
  • 86 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信