输入验证循环/使用 Python 读取文件 txt

Input Validation loop / read file txt with Python

我的第一个问题是我的文件没有被脚本读取,老实说我不知道​​为什么。

其次,问题是我的循环 "y" 或 "Y" 没有循环用户输入帐户的问题,它只是继续重复,直到我点击 "n" 或 "N" 退出....有效。 (所以我想我的循环在这个意义上可以正常工作)

我的现状 我有一个 txt 文件,我需要从中读取帐号。 我需要它循环并继续要求验证帐号,即使帐号是错误的。

我希望输出看起来像这样

------------我需要的输出----------------

>>>
Enter the account number to be validated: 456321
Account number 456321 is not valid.
Enter another card number? Enter Y or N: Y
Enter the account number to be validated: 5552012
Account number 5552012 is valid.
Enter another card number? Enter Y or N: N
>>>

------------结束需要输出-------------

------------我现在的输出--------

>>> 
============ RESTART: G:\Software Design\accounts.py ============
Enter the account number to be validated: 4453221
Account number 4453221 is not valid
Enter another card number? Enter Y or N: y
Enter another card number? Enter Y or N: n
>>> 

------------结束电流输出------------

--------我的代码----------

def main():

    #setting loop control
    another = 'y'

    try:
        # open file READ ONLY charge_accounts.txt
        infile = open('charge_accounts.txt', 'r')

        # Setting accountNum variable
        accountNum = int(input('Enter the account number to be validated: '))

        if accountNum in infile:
            accountNum = int(infile.readline(accountNum))
            print('Account number ' + str(accountNum) + ' is valid')
        else:
            print('Account number ' + str(accountNum) + ' is not valid')
            # Loop controls for other account inputs
            while another == 'y' or another == 'Y':
                # Get another account
                another = input('Enter another card number? ' + 'Enter Y or N: ')
                if another == 'n' or another == 'N':
                    break

        infile.close()

    # Extra credit +5 points ( catching errors )
    except IOError:
        print('An error occured trying to read')
        print('the file', charge_accounts.txt)
main()

关于你的循环,你想要重复的一切都需要在它里面。所以想想你写的东西,while another == y: 循环体 会重复。因此,我的建议是考虑 从哪里开始循环

此外,accountNum in infile: 将始终为假,因为您将 accountNumb 转换为 int,并且它需要保留为字符串。这是另一个提醒:

if accountNum in infile:
    accountNum = int(infile.readline(accountNum))
    print('Account number ' + str(accountNum) + ' is valid')

无论如何都不会像您想象的那样工作。当您检查 file 对象中是否有某些内容时,它会将流位置移动到末尾。这意味着当你 readline 它会 return 一个空字符串!如果您考虑一下,您实际上并不需要 readline