检查python中目录的权限

2 python chmod

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

谢谢!

lt_*_*ije 8

这两个答案都没有得到解决,尽管并不完全清楚这是OP想要的.这是一种递归方法(未经测试,但你明白了):

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
Run Code Online (Sandbox Code Playgroud)

stat的stdlib文档中描述了类似的东西 .


Bri*_*ian 5

看看os模块.特别是os.stat来查看权限位.

import  os

for filename in os.listdir(dirname):
   path=os.path.join(dirname, filename)
   if os.path.isdir(path):
       if (os.stat(path).st_mode & 0777) == 0775:
           print path
Run Code Online (Sandbox Code Playgroud)