如何在 Linux 机器上使用 Python 获取文件夹的所有者和组?

新手上路,请多包涵

如何在 Linux 下使用 Python 获取目录的所有者和组 ID?

原文由 dan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

使用 os.stat() 获取文件的 uid 和 gid。然后,使用 pwd.getpwuid()grp.getgrgid() 分别获取用户名和组名。

 import grp
import pwd
import os

stat_info = os.stat('/path')
uid = stat_info.st_uid
gid = stat_info.st_gid
print uid, gid

user = pwd.getpwuid(uid)[0]
group = grp.getgrgid(gid)[0]
print user, group

原文由 Ayman Hourieh 发布,翻译遵循 CC BY-SA 2.5 许可协议

自 Python 3.4.4 起, Pathpathlib 模块为此提供了一个很好的语法:

 from pathlib import Path
whatever = Path("relative/or/absolute/path/to_whatever")
if whatever.exists():
    print("Owner: %s" % whatever.owner())
    print("Group: %s" % whatever.group())

原文由 loxaxs 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题