我希望您能提供一个Python程序,给定一个目录,它将返回该目录中所有具有775 (
谢谢!
rwxrwxr-x
)权限的目录。谢谢!
两个答案都没有使用递归,但是不完全清楚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
Python标准库的文档中描述了类似的内容,文档地址为stat。
基于Brian的答案的紧凑型生成器:
import os
(fpath for fpath
in (os.path.join(dirname,fname) for fname in os.listdir(dirname))
if (os.path.isdir(fpath) and (os.stat(fpath).st_mode & 0777) == 0775))
一定要用Python吗?
你也可以使用find来完成:
"find . -perm 775"
path="location of file or directory"
if (oct(os.stat(path).st_mode)[-3:]=="775"):
print(path)