【发布时间】:2020-06-07 00:04:50
【问题描述】:
3.7 documentation 声明我们应该这样处理 OSError 异常:
except OSError as err:
print("OS error: {0}".format(err))
当我这样做时,程序退出仍然会出错。错误是:
File "F:/working/workfile.py", line 55, in main
OutFile = open(FileName, 'w')
OSError: [Errno 22] Invalid argument: 'bad<>file.txt'
完整的相关代码区域:
def main():
InvalidInput = True
while InvalidInput:
#Start Exception handling
try:
# Ask user for how many random numbers to create
NumberCount = int(input('How many numbers do you want to generate?'))
# Ask the user where the created numbers are to be stored
# Error out if invalid characters are used
FileName = input('Where do you want the files to be written to?')
# Catch the error if invalid characters are used
except OSError as err:
print("OS error: {0}".format(err))
print ('Please enter a valid path/filename.')
InvalidInput = True
except IOError:
print ('Please enter a valid path/filename.')
InvalidInput = True
except ValueError:
print ('Invalid number. Please enter only integers')
InvalidInput = True
else:
InvalidInput = False
OutFile = open(FileName, 'w')
for Number in range (NumberCount):
# Call the function(s) for generating random numbers
# and writing to the output file
ReturnNumber = RandomNumbers.RandomWriter ()
OutFile.write (str(ReturnNumber))
OutFile.write ("\n")
print ('Writing ', ReturnNumber)
# Close the file when finished
OutFile.close()
print ('Closing the open file.')
main()
使用有效字符键入文件名就可以了。我需要程序不会崩溃,并处理这个异常。关于我所缺少的任何建议?
谢谢
【问题讨论】:
-
产生异常的代码是什么样的?您确定抛出异常的行在您的 try:/except 块内吗?
-
看起来引发错误的行不在 try/catch 块内。它位于错误处理分支之一中。将行
out_file = open(file_name, 'w')放在注释#Catch the error..... 下方的块内,但请确保您的缩进是代码而不是注释。将 for 循环移到那里。 -
顺便说一句,Python 中的命名约定是小写和下划线表示局部变量和函数名,PascalCase 表示类名。
-
呵呵.. 比在代码审查期间在工作中被否决要好 =)
-
一个downvote是“downvotes come倒”?
标签: python python-3.x exception python-3.7