【发布时间】: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中明确返回任何东西(你应该返回文件),所以file是None,因此遍历这些行会说你不能遍历@987654326 @.