python - 如何修复错误异常以允许重试而不在 Python 中循环异常
问题描述
当用户输入文件名后引发 IOError 异常时,我正在尝试在 Python 2.7 中编写错误处理。
我在互联网上尝试了几种解决方案,包括:
异常后如何重试? 获取一个 Try 语句循环,直到获得正确的值
这是我的原始代码:
while True:
try:
with open (userFile, 'r') as txtFile:
for curLine in txtFile:
curLine = curLine.rstrip("\n\r")
idList.append(curLine)
except IOError:
print("File does not exist")
每当引发 IOError 异常时,它就会进入无限循环,一遍又一遍地打印“文件不存在”。在我通过添加范围来限制尝试的情况下,它会通过该范围,一遍又一遍地打印,然后退出脚本。有谁知道为什么在引发异常时它会一直循环?
解决方案
如果您将单独的关注点拆分为函数,这将容易得多,即(i)如果文件不存在则警告用户和(ii)将文件的内容读入行列表:
def read_file(f):
# you can't read a file line-by-line and get line endings that match '\n\r'
# the following will match what your code is trying to do, but perhaps not
# what you want to accomplish..?
return f.read().split("\n\r") # are you sure you haven't switched these..?
def checked_read_file(fname):
try:
with open(fname, 'rb') as fp: # you'll probably need binary mode to read \r
return read_file(fp)
except IOError:
print("File does not exist")
return False
然后你可以写你的while循环:
while True:
result = checked_read_file(user_file)
if result is not False: # this is correct since the empty list is false-y
break
user_file = input("Enter another filename: ") # or user_file = raw_input("...: ") if you're on Python 2
# here result is an array of lines from the file
推荐阅读
- python - 为什么 nx.draw_networkx_edges 在绘制图形边缘时不连接节点?
- javascript - react中如何实现usePrevious
- html - 使用 Pandoc 从 HTML 转换为 Markdown 时为代码块添加正确的语法名称
- entity-framework-core - 在当前工作目录中发现了多个项目。使用 --project 选项
- java - 如何在 Spring Boot jpa 中将 @OrderBy 与 Embeddable 一起使用
- java - 仅为 ONE 测试启用 spring 数据源
- reactjs - 反应如何覆盖父级中的子函数,
- python - 2d 列表的合并列表,它的分离正确,但是当它全部返回时,它是错误的,
- python - 熊猫:用正则表达式替换“类别”dtype
- java - 基于简单查找进行数据翻译的最佳实践 Apache Camel 方法