Reputation: 27991
in Python glob ignores "Permission denied" errors. Unfortunately I need to know if there was a directory which I can't read.
I could use os.walk() and fnmatch, but maybe there is a better solution?
Example:
user@pc:~
===> python
>>> import glob
>>> glob.glob('/root/*')
[]
There are files in /root, but user@pc is not allowed to read this directory.
A single Exception would not be enough. For example glob.glob('/var/log/*/*.log')
. I want to know which directories exist, but are unreadable.
Upvotes: 2
Views: 2977
Reputation: 40414
One way to get all the directories and files that cannot be read is indeed use os.walk
to traverse recursively a directory tree and then, for every directory and file, check permissions using os.access
:
import os
unreadable_dirs = []
unreadable_files = []
for dirpath, dirnames, filenames in os.walk('/var/log'):
for dirname in dirnames:
dirname = os.path.join(dirpath, dirname)
if not os.access(dirname, os.R_OK):
unreadable_dirs.append(dirname)
for filename in filenames:
filename = os.path.join(dirpath, filename)
if not os.access(filename, os.R_OK):
unreadable_files.append(filename)
print 'Unreadable directories:\n{0}'.format('\n'.join(unreadable_dirs))
print 'Unreadable files:\n{0}'.format('\n'.join(unreadable_files))
Note: You could write your own recursive function that traverses the directory structure, but you'll be basically duplicating os.walk
functionality, so I don't see the use case for glob.glob
.
Upvotes: 3