Reputation: 1525
I was starting to build a "Directory Explorer" GUI for a small program I wrote and was using Pathlib since I hadn't used it before. Unfortunately I got stuck pretty much right off the bat iterating over the root directory iterating like this:
import pathlib
current=pathlib.WindowsPath('/')
children=[child for child in current.iterdir() if child.is_dir()]
print(children)
Resulting in "PermissionError: [WinError 5] Access is denied: '\\Config.Msi'"
I tried using path.stat() in order to test the permission before attempting to determine if it's a directory, but it won't even let me get that far, so I'm at a bit of an impasse. I don't need the files/folders that I can't get permission for anyway, so I'd be more than happy to just pass over them, if anyone has any suggestions to do so.
Thanks in advance!
Upvotes: 1
Views: 2875
Reputation: 3947
Because it's easier to ask for forgiveness then to ask for permission, use Exceptions. I don't know anything about pathlib, but if you split up the code a little, the following should work
import pathlib
current=pathlib.WindowsPath('/')
children = []
for child in current.iterdir():
try:
if child.is_dir():
children.append(child)
except PermissionError:
pass
print(children)
Upvotes: 2