你如何在python中创建一个具有其他用户可以写入权限的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36745577/
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-19 18:17:15  来源:igfitidea点击:

How do you create in python a file with permissions other users can write

pythonpermissions

提问by Richard de Ree

How can I in python (3) create a file what others users can write as well. I've so far this but it changes the

我如何在 python (3) 中创建一个其他用户也可以编写的文件。到目前为止,我已经这样做了,但它改变了

os.chmod("/home/pi/test/relaxbank1.txt", 777)
with open("/home/pi/test/relaxbank1.txt", "w") as fh:
    fh.write(p1)  

what I get

我得到了什么

---sr-S--t 1 root root 12 Apr 20 13:21 relaxbank1.txt

---sr-S--t 1 root root 12 Apr 20 13:21relaxbank1.txt

expected (after doing in commandline $ sudo chmod 777 relaxbank1.txt )

预期(在命令行中执行 $ sudo chmod 777relaxbank1.txt 之后)

-rwxrwxrwx 1 root root 12 Apr 20 13:21 relaxbank1.txt

-rwxrwxrwx 1 root root 12 Apr 20 13:21relaxbank1.txt

采纳答案by user590028

The problem is your call to open()recreates the call. Either you need to move the chmod()to after you close the file, OR change the file mode to w+.

问题是您的呼叫open()重新创建了呼叫。您需要chmod()在关闭文件后移动到,或者将文件模式更改为w+.

Option1:

选项1:

with open("/home/pi/test/relaxbank1.txt", "w+") as fh:
    fh.write(p1)
os.chmod("/home/pi/test/relaxbank1.txt", 0o777)

Option2:

选项2:

os.chmod("/home/pi/test/relaxbank1.txt", 0o777)
with open("/home/pi/test/relaxbank1.txt", "w+") as fh:
    fh.write(p1)

Comment: Option1 is slightly better as it handles the condition where the file may not already exist (in which case the os.chmod()will throw an exception).

评论:Option1 稍微好一点,因为它处理文件可能不存在的情况(在这种情况下os.chmod()将抛出异常)。

回答by AXO

If you don't want to use os.chmodand prefer to have the file created with appropriate permissions, then you may use os.opento create the appropriate file descriptor and then openthe descriptor:

如果您不想使用os.chmod并且更喜欢使用适当的权限创建文件,那么您可以使用os.open创建适当的文件描述符,然后open使用描述符:

import os
# The default umask is 0o22 which turns off write permission of group and others
os.umask(0)
with open(os.open('filepath', os.O_CREAT | os.O_WRONLY, 0o777), 'w') as fh:
  fh.write(...)

Python 2 Note:

Python 2 注意:

The built-in open()in Python 2.x doesn't support opening by file descriptor. Use os.fdopeninstead; otherwise you'll get:

Python 2.x 中的内置open()不支持通过文件描述符打开。使用os.fdopen代替; 否则你会得到:

TypeError: coercing to Unicode: need string or buffer, int found.