本文介绍了你如何在python中创建一个具有其他用户可以写入权限的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我得到了什么

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

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

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

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

推荐答案

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

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

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 注意:

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

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

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

这篇关于你如何在python中创建一个具有其他用户可以写入权限的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 08:37