【发布时间】:2020-10-14 12:16:31
【问题描述】:
我有一个函数可以成功获取顶层文件夹的所有文件路径。但是,当它遇到我无权访问的文件夹时,循环会中断。
如何跳过此错误,以便在不中断循环的情况下提取所有其余文件路径?
我正在考虑使用try 和except,但我不确定如何实现。有什么想法吗?
这是我的代码:
def get_list_of_files(dir_name):
"""
Gets all the filepaths.
:param: dir_name: the name of the directory to parse
: return all of the filepaths
"""
list_files = os.listdir(dir_name)
all_files = list()
for item in list_files:
full_path = os.path.join(dir_name, item)
if os.path.isdir(full_path):
all_files = all_files + get_list_of_files(full_path)
else:
all_files.append(full_path)
return all_files
【问题讨论】:
-
请查看 try/except 块,这将为您指明正确的方向
-
当然,如果不先查一下,我不会问这个问题。在 for 循环的顶部实现“尝试”是否可行,除了: OSError ?欢呼
-
哪个语句中断/给出错误?
标签: python function loops directory try-catch