当用户输入文件名时,我需要包括某种形式的错误处理,以便如果他们放入一个不在程序目录中的文件名,那么它将与错误消息一起出现。这是目前的代码:
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/,除非我像这样包含它:
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())))
然后我得到以下错误:
文件第28行,in表示文件中的行: NameError:未定义名称‘
’
我知道可能有一个非常简单的解决方案,但我正在努力解决这个问题。
发布于 2019-03-15 05:51:05
您应该将所有可能出现错误的行都包含在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
中的局部变量,您在作用域之外调用它。
https://stackoverflow.com/questions/55172524
复制相似问题