Python cause of "AttributeError: 'NoneType' object has no attribute 'readline'"

Python cause of "AttributeError: 'NoneType' object has no attribute 'readline'"

我正在尝试从每行有 1 个整数的文件中打印整数,并打印它们的总和。一切似乎都工作正常,除非我输入了错误的文件名,循环返回,然后输入正确的文件名。该程序仍然输出正确的信息,但随后出现错误: “AttributeError:'NoneType' 对象没有属性 'readline'”。为什么会这样?

def main():
    listnums = filetolist()
    print(f'numbers in file: {listnums}')
    print(f' sum of before mentioned numbers is: {sum(listnums)}')


# opens file
def openfile():
    try:
        file = open(input("what is the file named including the file extension?"), "r")
        return file
    except IOError:
        tryagain = input("File could not be found \n" + "if you would like try again type 1 and press enter, to exit press enter")
        if tryagain == "1":
            main()
        else:
            exit()


# converts file to list
def filetolist():
    file = openfile()
    line = file.readline()
    nums = []
    linenumber = 1
    while line != "":
        nums += [verifyint(line, linenumber)]
        line = file.readline()
        linenumber += 1
    file.close()
    return nums


# verifies number is an int
def verifyint(num, linenumber):
    try:
        numint = int(num)
        return numint
    except ValueError:
        print(f'Invalid value on line #{linenumber}')
        exit()


main()

我认为(我可能是错的)问题在于,当您无法读取文件并重试时,您需要重新调用 openfile 而不是整个 main。 如果你调用整个 main 你打开一个新文件执行所有例程然后什么都不返回。

试一试然后告诉我它是否有效

def openfile():
    try:
        file = open(input("what is the file named including the file extension?"), "r")
        return file
    except IOError:
        tryagain = input("File could not be found \n" + "if you would like try again type 1 and press enter, to exit press enter")
        if tryagain == "1":
            return openfile()
        else:
            exit()

这里是截图

打到except块时,没有return语句,所以这个函数returns None after 运行 main() 再次

与其有效地递归,不如适当地引发错误并使用适当的循环

def filetolist(filename):
    with open(filename) as f:
        return [int(line.rstrip()) for line in f]

def main():
    while True:
        filename = input("what is the file named including the file extension?")
        try:
            listnums = filetolist(filename)
            print(f'numbers in file: {listnums}')
            print(f' sum of before mentioned numbers is: {sum(listnums)}')
        except ValueError, IOError:
            again = input('Error! Try again? (y/n)')
            if again.lower() != 'y':
                break

main()