Python 如果我最初输入了正确的输入,函数就可以工作,但如果我尝试了错误的输入,然后输入了正确的输入,它会给我一个属性错误
我有一个try/except语句:Python 如果我最初输入了正确的输入,函数就可以工作,但如果我尝试了错误的输入,然后输入了正确的输入,它会给我一个属性错误,python,try-except,Python,Try Except,我有一个try/except语句: def get_file(): myfile = input("Enter the name of the file to read:\n") try: open_myfile = open(myfile, "r") return open_myfile except: print('Could not open file.')
def get_file():
myfile = input("Enter the name of the file to read:\n")
try:
open_myfile = open(myfile, "r")
return open_myfile
except:
print('Could not open file.')
get_file()
然后是一个函数,如果代码用于检查拼写:
def checktext(textfile):
sp = spellchecker(textfile)
lines_text = textfile.readlines()
true = 0
false = 0
for line in lines_text:
for word in line.split():
c_word = sp.check(word)
if c_word == True:
true =+ 1
else:
print("Possible Spelling Error on line", lines_text.index(line),":",c_word)
false = false + 1
percent = ((true)/(true+false))*100
print(false, "words that passed the spell checker.")
print(true, "words failed the spell checker.")
print(percent, "% of words passed.")
如果我最初输入了一个可使用的文件,这就可以工作了。如果我输入了除可用文件以外的任何内容,它将允许我输入另一个可用文件,但是,代码将给出属性错误:
“NoneType”对象没有属性“readlines”。如果get_file()通过except语句,我不知道为什么代码在我输入正确的文件后不起作用。你在哪里调用checktext?我怀疑你想检查
打开_myfile.exists()
。。。您可以open()
不存在的文件get\u file
是否有意调用自身?是的,因为您需要返回get\u file()
。或者,如果您点击execept
,第一个调用总是返回None
。但是您应该只使用while
循环,而不是递归。这在Python中更为惯用