在python中检查目录的权限 [英] check permissions of directories in python

查看:102
本文介绍了在python中检查目录的权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个给定目录的python程序,它将返回该目录中所有具有775( rwxrwxr-x )权限的目录

i want a python program that given a directory, it will return all directories within that directory that have 775 (rwxrwxr-x) permissions

谢谢!

推荐答案

这两个答案都不会重复出现,尽管还不很清楚这就是OP想要的。这是一种递归方法(未经测试,但您知道了):

Neither answer recurses, though it's not entirely clear that that's what the OP wants. Here's a recursive approach (untested, but you get the idea):

import os
import stat
import sys

MODE = "775"

def mode_matches(mode, file):
    """Return True if 'file' matches 'mode'.

    'mode' should be an integer representing an octal mode (eg
    int("755", 8) -> 493).
    """
    # Extract the permissions bits from the file's (or
    # directory's) stat info.
    filemode = stat.S_IMODE(os.stat(file).st_mode)

    return filemode == mode

try:
    top = sys.argv[1]
except IndexError:
    top = '.'

try:
    mode = int(sys.argv[2], 8)
except IndexError:
    mode = MODE

# Convert mode to octal.
mode = int(mode, 8)

for dirpath, dirnames, filenames in os.walk(top):
    dirs = [os.path.join(dirpath, x) for x in dirnames]
    for dirname in dirs:
        if mode_matches(mode, dirname):
            print dirname

stdlib文档中有关
stat

Something similar is described in the stdlib documentation for stat.

这篇关于在python中检查目录的权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆