Python - 无法识别异常处理



所以我在异常处理方面遇到了问题,我正在运行Python 3.6.3。这是我的代码:

txt = ""
txtFile = input("gimme a file.")
f = open(txtFile, "r")
try:    
    for line in f:
        cleanedLine = line.strip() 
        txt += cleanedLine
except FileNotFoundError:
    print("!")

因此,如果我尝试出现输入错误的错误而不是打印!我仍然收到错误:

Traceback (most recent call last):
File "cleaner.py", line 11, in <module>
    f = open(txtFile, "r")
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistentfile'

我尝试过交换OSError,我也尝试了except:,这告诉我我做错了什么(因为我一开始就不应该这样做(,并且因为我知道except:应该捕获所有异常。

很简单,你打开了异常之外的东西。

txt = []
txtFile = input("gimme a file.")
try:        
    f = open(txtFile, "r")
    for line in f.read().split('n'):
        cleanedLine = line.strip()
        txt.append(cleanedLine)
except FileNotFoundError:
    print("!")

您的尝试捕获是通过行封装循环。

当您尝试在 try 块之外打开文件时,会发生错误。

最新更新