python - 在python中更改文件的权限
问题描述
我正在尝试执行以下操作:
编写代码检查目录'files'中每个文件的权限。如果 'group' 的权限不是 'rwx',则更改该文件的权限如下: 'user' 可以 rwx, 'group' 可以 rwx, 'other' 不能做任何事情。
我尝试了以下方法:
import os
import stat
path = '/home/myname/files'
for r, d, f in os.walk(path):
for file in f:
if not os.access(file, stat.S_IRWXU):
print("User cannot rwx: ", file)
os.chmod(file, stat.S_IRWXU)
if os.access(file, stat.S_IRWXG) == 0:
print("Group cannot rwx: ", file)
os.chmod(file, stat.S_IRWXG)
但是,我注意到两件事。
- 无论我尝试什么,我都无法检查它是否不是 rwx。它忽略'if not','== 0' 也不起作用。
- 调用 S_IRWXU 会更改我想要的权限,但是当我稍后调用“S_IRWXG”时,用户权限就会消失。这不是我想要的。我该如何解决这两个问题?
解决方案
以下是我认为您应该修复代码的方法:
def isGroupRWX(file):
# check the group bits of the file mode are all set (R, W and X)
mode = os.stat(file).st_mode
return (mode and 0b111000) == 0b111000
def fixPermissions(file):
# set permissions for both user and group to RWX
os.chmod(file, stat.S_IRWXG or stat.S_IRWXU)
您需要检查os.stat
以获取文件的模式,因为您需要明确检查组权限,而不仅仅是当前用户是否可以访问该文件。
您可以将模式组合传递给以os.chmod
同时设置它们,从而解决您的第二个问题。
推荐阅读
- c - 在内核中使用字节序特定类型 __be32/__be16/__le32/__le16
- twitter-bootstrap-3 - 从 kartik-v 自定义对话框中删除确定按钮
- c - 使用 fprintf 和 fscanf 时出错
- google-bigquery - BigQuery 以逗号分隔值的形式获取列
- mysql - MySQL在比较两个表时找到不存在的值
- visual-studio-2015 - VS2015 C++ 项目中不存在目标“PreLinkEvent”
- sql - 没有 Not In 和 In 的 SQL 查询优化
- razor - 使用 Identity UI 作为库在 ASP.NET Core 2.1 中授权注册页面
- c# - 如何创建从泛型类扩展的抽象类
- javascript - AJAX响应文本到全局变量