【问题标题】:NoneType error when opening file打开文件时出现NoneType错误
【发布时间】:2016-10-12 10:55:13
【问题描述】:

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

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

我认为这只是一个愚蠢的错误,但我似乎找不到它。 感谢您的宝贵时间!

【问题讨论】:

  • 你永远不会在open_file 中明确返回任何东西(你应该返回文件),所以fileNone,因此遍历这些行会说你不能遍历@987654326 @.

标签: python nonetype


【解决方案1】:

您的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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多