如果我最初输入正确的输入,则该函数有效,但是如果我输入了错误的输入,然后输入正确的输入,则会给我一个属性错误

问题描述

我有一条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.')
         
        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语句通过,代码却无法工作。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)