Skip to main content
 首页 » 编程设计

python之如何在这段代码中包含文件名错误处理

2024年11月24日9rubylouvre

当用户输入文件名时,我需要包含某种形式的错误处理,这样如果他们输入的文件名不在程序目录中,那么它将显示一条错误消息。这是目前的代码:

board = []  
fileinput = input("Please enter your text file name:")         
filename = fileinput + ".txt"    
file = open(filename, "r+") 
for lines in file: 
    board.append(list(map(int,lines.split()))) 

我不确定在哪里包含 try/except 就像我这样包含它一样:

board = []  
fileinput = input("Please enter your text file name:")         
filename = fileinput + ".txt" 
try: 
    file = open(filename, "r+") 
    except: 
        print("Error: File not found") 
    for lines in file: 
        board.append(list(map(int,lines.split()))) 

然后我得到以下错误:

line 28, in for lines in file: NameError: name 'file' is not defined

我知道可能有一个非常简单的解决方案,但我正在努力解决这个问题。

请您参考如下方法:

你应该在try下包含所有可能出错的行,所以:

board = []  
fileinput = input("Please enter your text file name:")         
filename = fileinput + ".txt" 
try: 
    file = open(filename, "r+") 
    for lines in file: 
        board.append(list(map(int,lines.split()))) 
except: 
    print("Error: File not found") 

按照您介绍的方式,程序会尝试忽略错误并继续执行,最后以 NameError: name 'file' is not defined

在您的案例中,第二个问题是范围 - file 是 try 中的局部变量,您在范围之外调用它。