首页 > 解决方案 > 在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)

但是,我注意到两件事。

  1. 无论我尝试什么,我都无法检查它是否不是 rwx。它忽略'if not','== 0' 也不起作用。
  2. 调用 S_IRWXU 会更改我想要的权限,但是当我稍后调用“S_IRWXG”时,用户权限就会消失。这不是我想要的。我该如何解决这两个问题?

标签: pythonunix

解决方案


以下是我认为您应该修复代码的方法:

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同时设置它们,从而解决您的第二个问题。


推荐阅读