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

将 txt 文件的多行与 python 中的单个变量进行比较

将 txt 文件的多行与 python 中的单个变量进行比较

largeQ 2023-05-23 16:38:29
我想知道如何将文本文件的多行与单个变量进行比较。我已经部分工作了,但它只与文本文件的最后一行进行比较def loginSetup():    global loginSelector    global accountInt    loginSelector = int(input("Select Action:"))            if loginSelector == 1:        #login        print ("action complete")    if loginSelector == 2:        #sign up          accountInt = int(input("Input 4 Digit Pin:"))        while (accountInt >= 9999 or accountInt <= 999):            print("ERROR\nTry Again")            accountInt = int(input("Input 4 Digit Pin:"))        accountInt = str(accountInt)        with open('Account.txt', 'r') as rf:            for line in rf:                if (line == str(accountInt)):                    print("error")        with open('Account.txt', 'a') as f:            f.write('\n')            f.write(accountInt)            while True:     loginSetup() 
查看完整描述

1 回答

?
BIG阳

TA贡献1859条经验 获得超6个赞

这是因为您不是先写一行文本后跟换行符的标准方式,而是先写换行符。所以文件的最后一行没有尾随换行符(并允许比较在那里成功)。

在循环中,line将是一些在末尾带有换行符的文本(除了最后一行之外的所有文本),并且str(AccountInt)永远不会有换行符。所以不可能匹配。

在比较之前,您需要从字符串中去除换行符。


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

添加回答

举报

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