Python Pathlib 在使用 Iterdir() 时避免权限错误
Python Pathlib avoid Permission Errors when using Iterdir()
我开始为我编写的一个小程序构建一个 "Directory Explorer" GUI,并且使用 Pathlib,因为我以前没有使用过它。不幸的是,我马上就卡住了,像这样迭代根目录:
import pathlib
current=pathlib.WindowsPath('/')
children=[child for child in current.iterdir() if child.is_dir()]
print(children)
导致 "PermissionError: [WinError 5] Access is denied: '\Config.Msi'"
我尝试使用 path.stat() 来测试权限,然后再尝试确定它是否是一个目录,但它甚至不会让我走那么远,所以我有点僵局。我不需要 files/folders,无论如何我都无法获得许可,所以我很乐意忽略它们,如果有人有任何建议的话。
提前致谢!
因为是 easier to ask for forgiveness then to ask for permission, use Exceptions。我对 pathlib 一无所知,但如果你稍微拆分一下代码,下面的代码应该可以工作
import pathlib
current=pathlib.WindowsPath('/')
children = []
for child in current.iterdir():
try:
if child.is_dir():
children.append(child)
except PermissionError:
pass
print(children)
我开始为我编写的一个小程序构建一个 "Directory Explorer" GUI,并且使用 Pathlib,因为我以前没有使用过它。不幸的是,我马上就卡住了,像这样迭代根目录:
import pathlib
current=pathlib.WindowsPath('/')
children=[child for child in current.iterdir() if child.is_dir()]
print(children)
导致 "PermissionError: [WinError 5] Access is denied: '\Config.Msi'"
我尝试使用 path.stat() 来测试权限,然后再尝试确定它是否是一个目录,但它甚至不会让我走那么远,所以我有点僵局。我不需要 files/folders,无论如何我都无法获得许可,所以我很乐意忽略它们,如果有人有任何建议的话。
提前致谢!
因为是 easier to ask for forgiveness then to ask for permission, use Exceptions。我对 pathlib 一无所知,但如果你稍微拆分一下代码,下面的代码应该可以工作
import pathlib
current=pathlib.WindowsPath('/')
children = []
for child in current.iterdir():
try:
if child.is_dir():
children.append(child)
except PermissionError:
pass
print(children)