这是一个简单的例子。
它是一个递归函数(即它调用自身)尝试列出目录(父级
)的内容(child
ren)。
如果
child
是一个文件,它只打印文件名。如果
child
是一个目录,它会打印目录的名称并尝试列出它的内容,等等在。如果
child
是一个目录,但是用户没有权限读取它的内容,一个异常(OSError
) 被抛出。所以我们用try:
和except OSError: continue
包裹它以防止循环终止。它说:“当特权不足时,不要停止;继续前进;摆脱它,继续前进到下一个。”
#!/usr/bin/env python3
import os
def list_children(parent):
<b>for child in os.listdir(parent):</b>
try:
if os.isdir(child):
print(child)
list_children(child)
elif os.isfile(child):
print(child)
except OSError:
continue
list_children('/home')
但是,continue
只在循环体内部起作用(如for
、while
),当出现异常时你能做什么由实际的 for
(或 while
)循环表达式(即紧接在循环主体之前的行)抛出,如 os.listdir()
上面例子中的函数?
最佳答案
如果无法生成您正在循环的内容,则无需继续
(即,如果没有循环,则无法进入循环的下一次迭代)。只需将整个内容包装在 try
中,或者可能只是将第一个顶级 listdir
包装起来,以便控制缩进:
def list_children(parent: str) -> None:
try:
top_level = os.listdir(parent)
except OSError:
top_level = []
for child in top_level:
try:
if os.isdir(child):
print(child)
list_children(child)
elif os.isfile(child):
print(child)
except OSError:
continue
关于python - 当异常在实际的 'continue' 语句中时,你如何 'for'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58807172/