打开文件时出现NoneType错误

时间:2016-10-12 02:51:42

标签: python nonetype

所以我一直试图弄清楚为什么它会给我这个错误。如果我这样说:

def open_file():
    fp = open("ABC.txt")
    return fp

file = open_file()

count = 1

for line in file:
    if count == 9:
        line9 = line
    if count == 43:
        line43 = line
#blahblahblah more programming

这有效,但这给了我NoneType对象不可迭代:

def open_file():
    while True:
        file = input("Enter a file name: ")
        try:
            open(file)
            break
        except FileNotFoundError:
            print("Error. Please try again.")
            print()

file = open_file()

count = 1

for line in file:  #here is where I get the error
    if count == 9:
        line9 = line
    if count == 43:
        line43 = line

我认为这只是一些愚蠢的错误,但我似乎无法找到它。 谢谢你的时间!

1 个答案:

答案 0 :(得分:2)

您的open_file函数没有return语句,因此返回None。你应该尝试像

这样的东西
def open_file():
    while True:
        file = input("Enter a file name: ")
        try:
            return open(file)
        except FileNotFoundError:
            print("Error. Please try again.")
            print()
相关问题