所以我一直试图弄清楚为什么它会给我这个错误。如果我这样说:
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
我认为这只是一些愚蠢的错误,但我似乎无法找到它。 谢谢你的时间!
答案 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()