Python模块os.chmod(file,664)不会将权限更改为rw-rw-r--而是-w--wx ---- [英] Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----
问题描述
最近我正在使用Python模块os,当我尝试更改文件的权限时,没有得到预期的结果.例如,我打算将权限更改为rw-rw-r-,
Recently I am using Python module os, when I tried to change the permission of a file, I did not get the expected result. For example, I intended to change the permission to rw-rw-r--,
os.chmod("/tmp/test_file", 664)
所有权许可实际上是-w--wx ---(230)
The ownership permission is actually -w--wx--- (230)
--w--wx--- 1 ag ag 0 Mar 25 05:45 test_file
但是,如果我在代码中将664更改为0664,结果就是我所需要的,例如
However, if I change 664 to 0664 in the code, the result is just what I need, e.g.
os.chmod("/tmp/test_file", 0664)
结果是:
-rw-rw-r-- 1 ag ag 0 Mar 25 05:55 test_file
有人可以帮助解释为什么前导0对于获得正确结果如此重要吗?
Could anybody help explaining why does that leading 0 is so important to get the correct result?
推荐答案
在不同的论坛上找到了该解决方案
Found this on a different forum
如果您想知道为什么前导零很重要,那是因为 权限设置为八进制整数,Python自动生成 将前导零的任何整数视为八进制.所以os.chmod("file", 484)(十进制)将得出相同的结果.
If you're wondering why that leading zero is important, it's because permissions are set as an octal integer, and Python automagically treats any integer with a leading zero as octal. So os.chmod("file", 484) (in decimal) would give the same result.
您正在做的是传递664
,八进制为1230
What you are doing is passing 664
which in octal is 1230
您需要的是
os.chmod("/tmp/test_file", 436)
[更新]注意,对于Python 3,您的前缀为0o(零哦).例如,0o666
这篇关于Python模块os.chmod(file,664)不会将权限更改为rw-rw-r--而是-w--wx ----的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!