在 Python 中更改文件权限

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16249440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:07:19  来源:igfitidea点击:

Changing file permission in Python

pythonfile-permissions

提问by Abul Hasnat

I am trying to change permission of a file access:

我正在尝试更改文件访问权限:

os.chmod(path, mode)

I want to make it read-only:

我想让它只读:

os.chmod(path, 0444)

Is there any other way make a file read-only?

有没有其他方法使文件只读?

回答by Inbar Rose

os.chmod(path, 0444)isthe Python command for changing file permissions in Python 2.x. For a combined Python 2 and Python 3 solution, change 0444to 0o444.

os.chmod(path, 0444)用于在 Python 2.x 中更改文件权限的 Python 命令。对于组合的 Python 2 和 Python 3 解决方案,更改04440o444.

You could always use Python to call the chmod command using subprocess. I think this will only work on Linux though.

您始终可以使用 Python 调用 chmod 命令subprocess。我认为这仅适用于 Linux。

import subprocess

subprocess.call(['chmod', '0444', 'path'])

回答by John La Rooy

os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)

stat

状态

The following flags can also be used in the mode argument of os.chmod():

stat.S_ISUIDSet UID bit.

stat.S_ISGIDSet-group-ID bit. This bit has several special uses. For a directory it indicates that BSD semantics is to be used for that directory: files created there inherit their group ID from the directory, not from the effective group ID of the creating process, and directories created there will also get the S_ISGID bit set. For a file that does not have the group execution bit (S_IXGRP) set, the set-group-ID bit indicates mandatory file/record locking (see also S_ENFMT).

stat.S_ISVTXSticky bit. When this bit is set on a directory it means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory, or by a privileged process.

stat.S_IRWXUMask for file owner permissions.

stat.S_IRUSROwner has read permission.

stat.S_IWUSROwner has write permission.

stat.S_IXUSROwner has execute permission.

stat.S_IRWXGMask for group permissions.

stat.S_IRGRPGroup has read permission.

stat.S_IWGRPGroup has write permission.

stat.S_IXGRPGroup has execute permission.

stat.S_IRWXOMask for permissions for others (not in group).

stat.S_IROTHOthers have read permission.

stat.S_IWOTHOthers have write permission.

stat.S_IXOTHOthers have execute permission.

stat.S_ENFMTSystem V file locking enforcement. This flag is shared with S_ISGID: file/record locking is enforced on files that do not have the group execution bit (S_IXGRP) set.

stat.S_IREADUnix V7 synonym for S_IRUSR.

stat.S_IWRITEUnix V7 synonym for S_IWUSR.

stat.S_IEXECUnix V7 synonym for S_IXUSR.

以下标志也可用于 os.chmod() 的 mode 参数:

stat.S_ISUID设置 UID 位。

stat.S_ISGID设置组 ID 位。这个位有几个特殊用途。对于目录,它表示该目录将使用 BSD 语义:在那里创建的文件从目录继承其组 ID,而不是从创建过程的有效组 ID,并且在那里创建的目录也将设置 S_ISGID 位。对于未设置组执行位 (S_IXGRP) 的文件,set-group-ID 位指示强制文件/记录锁定(另请参阅 S_ENFMT)。

stat.S_ISVTX粘一点。当在目录上设置此位时,意味着该目录中的文件只能由文件所有者、目录所有者或特权进程重命名或删除。

stat.S_IRWXU文件所有者权限的掩码。

stat.S_IRUSR所有者具有读取权限。

stat.S_IWUSR所有者有写权限。

stat.S_IXUSR所有者具有执行权限。

stat.S_IRWXG组权限掩码。

stat.S_IRGRP组具有读取权限。

stat.S_IWGRP组有写权限。

stat.S_IXGRP组具有执行权限。

stat.S_IRWXO屏蔽其他人的权限(不在组中)。

stat.S_IROTH其他人有阅读权限。

stat.S_IWOTH其他人有写权限。

stat.S_IXOTH其他人有执行权限。

stat.S_ENFMTSystem V 文件锁定强制执行。此标志与 S_ISGID 共享:对未设置组执行位 (S_IXGRP) 的文件强制执行文件/记录锁定。

stat.S_IREADS_IRUSR 的 Unix V7 同义词。

stat.S_IWRITES_IWUSR 的 Unix V7 同义词。

stat.S_IEXECS_IXUSR 的 Unix V7 同义词。

回答by Chip Hogg

All the current answers clobber the non-writingpermissions: they make the file readable-but-not-executable for everybody. Granted, this is because the initial question asked for 444permissions -- but we can do better!

当前所有的答案都破坏了非写入权限:它们使文件对每个人都可读但不可执行。当然,这是因为最初的问题要求获得444权限——但我们可以做得更好!

Here's a solution that leaves all the individual "read" and "execute" bits untouched. I wrote verbose code to make it easy to understand; you can make it more terse if you like.

这是一个使所有单独的“读取”和“执行”位保持不变的解决方案。我编写了冗长的代码以使其易于理解;如果你愿意,你可以让它更简洁。

import os
import stat

def remove_write_permissions(path):
    """Remove write permissions from this path, while keeping all other permissions intact.

    Params:
        path:  The path whose permissions to alter.
    """
    NO_USER_WRITING = ~stat.S_IWUSR
    NO_GROUP_WRITING = ~stat.S_IWGRP
    NO_OTHER_WRITING = ~stat.S_IWOTH
    NO_WRITING = NO_USER_WRITING & NO_GROUP_WRITING & NO_OTHER_WRITING

    current_permissions = stat.S_IMODE(os.lstat(path).st_mode)
    os.chmod(path, current_permissions & NO_WRITING)

Why does this work?

为什么这样做?

As John La Rooy pointed out,stat.S_IWUSRbasically means "the bitmask for the user's write permissions". We want to set the corresponding permission bit to 0. To do that, we need the exact oppositebitmask (i.e., one with a 0 in that location, and 1's everywhere else). The ~operator, which flips all the bits, gives us exactly that. If we apply this to any variable via the "bitwise and" operator (&), it will zero out the corresponding bit.

正如John La Rooy 指出的stat.S_IWUSR基本上意味着“用户写权限的位掩码”。我们想将相应的权限位设置为 0。为此,我们需要完全相反的位掩码(即,该位置为 0,其他位置为 1)。~翻转所有位的运算符,正是给我们的。如果我们通过“按位与”运算符 ( &) 将其应用于任何变量,它会将相应的位清零。

We need to repeat this logic with the "group" and "other" permission bits, too. Here we can save some time by just &'ing them all together (forming the NO_WRITINGbit constant).

我们也需要用“组”和“其他”权限位重复这个逻辑。在这里,我们可以&通过将它们全部放在一起(形成NO_WRITING位常数)来节省一些时间。

The last step is to get the current file's permissions, and actually perform the bitwise-and operation.

最后一步是获取当前文件的权限,并实际执行按位与操作。

回答by solgar

No need to remember flags. Remember that you can always do:

无需记住标志。请记住,您始终可以:

subprocess.call(["chmod", "a-w", "file/path])

subprocess.call(["chmod", "a-w", "file/path])

Not portable but easy to write and remember:

不便携但易于编写和记忆:

  • u - user
  • g - group
  • o - other
  • a - all
  • + or - (add or remove permission)
  • r - read
  • w - write
  • x - execute
  • u - 用户
  • g - 组
  • o - 其他
  • 一个 - 所有
  • + 或 -(添加或删除权限)
  • r - 阅读
  • w - 写
  • x - 执行

Refer man chmodfor additional options and more detailed explanation.

man chmod有关其他选项和更详细的说明,请参阅。

回答by Gitanoqevaporelmundoentero

Simply include permissions integer in octal (works for both python 2 and python3):

只需在八进制中包含权限整数(适用于 python 2 和 python3):

os.chmod(path, 0o444)

回答by Jonathan H

FYI here is a function to convert a permission string with 9 characters (e.g. 'rwsr-x-wt') to a mask that can be used with os.chmod().

仅供参考,这是一个将具有 9 个字符的权限字符串(例如“rwsr-x-wt”)转换为可与os.chmod().

def perm2mask(p):

    assert len(p) == 9, 'Bad permission length'
    assert all(p[k] in 'rw-' for k in [0,1,3,4,6,7]), 'Bad permission format (read-write)'
    assert all(p[k] in 'xs-' for k in [2,5]), 'Bad permission format (execute)'
    assert p[8] in 'xt', 'Bad permission format (execute other)'

    m = 0

    if p[0] == 'r': m |= stat.S_IRUSR 
    if p[1] == 'w': m |= stat.S_IWUSR 
    if p[2] == 'x': m |= stat.S_IXUSR 
    if p[2] == 's': m |= stat.S_IXUSR | stat.S_ISUID 

    if p[3] == 'r': m |= stat.S_IRGRP 
    if p[4] == 'w': m |= stat.S_IWGRP 
    if p[5] == 'x': m |= stat.S_IXGRP 
    if p[5] == 's': m |= stat.S_IXGRP | stat.S_ISGID 

    if p[6] == 'r': m |= stat.S_IROTH 
    if p[7] == 'w': m |= stat.S_IWOTH 
    if p[8] == 'x': m |= stat.S_IXOTH 
    if p[8] == 't': m |= stat.S_IXOTH | stat.S_ISVTX

    return m

Note that setting SUID/SGID/SVTX bits will automatically set the corresponding execute bit. Without this, the resulting permission would be invalid (STcharacters).

请注意,设置 SUID/SGID/SVTX 位将自动设置相应的执行位。没有这个,由此产生的权限将是无效的(ST字符)。

回答by Megha Chovatiya

Just add 0 before the permission number:
For example - we want to give all permissions - 777
Syntax: os.chmod("file_name" , permission)

只需在权限编号前添加 0:
例如 - 我们要授予所有权限 - 777
语法: os.chmod("file_name" , permission)

import os
os.chmod("file_name" , 0777)

Python version 3.7 does not support this syntax. It requires '0o' prefix for octal literals - this is the comment I have got in PyCharm

Python 3.7 版不支持此语法。它需要八进制文字的“0o”前缀 - 这是我在 PyCharm 中得到的评论

So for python 3.7, it will be

所以对于python 3.7,它将是

import os
os.chmod("file_name" , 0o777)

回答by SuperNova

You can use, pathlib also

您也可以使用 pathlib

from pathlib import Path

fl = Path("file_name")

fl.chmod(0o444)