我有一个函数可以成功获取顶级文件夹的所有文件路径。但是,当循环运行到我无权访问的文件夹时,循环中断。
如何跳过此错误,以便可以提取所有其他文件路径而不会中断循环?
我当时在考虑使用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",使代码"try"像往常一样执行,当他遇到OSError异常时,他开始在"except"下执行事情,这在我的示例中,传递到list_files中的下一项。
list_files = os.listdir(dir_name)
all_files = list()
for item in list_files:
try:
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)
except OSError:
# maybe some other code you want to execute
continue
return all_files