glob,但不要忽略“权限被拒绝”

发布于 2024-12-26 12:18:11 字数 346 浏览 0 评论 0 原文

Python glob 会忽略“权限被拒绝”错误。不幸的是我需要知道是否有一个我无法读取的目录。

我可以使用 os.walk() 和 fnmatch,但也许有更好的解决方案?

示例:

user@pc:~
===> python
>>> import glob
>>> glob.glob('/root/*')
[]

/root 下有文件,但 user@pc 不允许读取该目录。

单个异常是不够的。例如glob.glob('/var/log/*/*.log')。我想知道哪些目录存在,但不可读。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枯寂 2025-01-02 12:18:11

获取所有无法读取的目录和文件的一种方法确实是使用 os.walk 递归地遍历目录树,然后对于每个目录和文件,使用 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))

注意:您可以编写自己的递归函数来遍历目录结构,但基本上会复制 os.walk< /code> 功能,所以我没有看到 glob.glob 的用例。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文