python - 为什么我无法在 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 中的字符串与输入的字符串不同,则应将该字符串添加到文件中。#但我的程序每次(无论我输入什么)都不做任何事情
解决方案
这是因为您以模式打开文件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)
推荐阅读
- python - 删除嵌套字典的重复值
- java - Java Getter 和 Setter 在 Swing ActionListner 中不起作用
- python - 使用 PIL 包在图像上编写日语文本
- go - Kafka 偏移量有时会在消费者重启后重置
- visual-studio-code - Tensorboard 在浏览器和 vscode 中什么都不显示
- pandas - 这对行和列意味着什么?
- python - 在 Python 中的 Visual Stdio Code 中导入 ocrmypdf
- deep-learning - MASK-RCNN的自定义训练类怎么写?
- javascript - 新成员加入 wix 时自动分配角色
- android - Firebase 云消息传递返回无效注册