How do you create in python a file with permission

2019-02-09 10:51发布

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)  

what I get

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

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

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

3条回答
放我归山
2楼-- · 2019-02-09 11:10

This is a robust method

#!/usr/bin/env python3
import stat
import os
path = 'outfile.txt'
with open(path, 'w') as fh:
    fh.write('blabla\n')
st = os.stat(path)
os.chmod(path, st.st_mode | stat.S_IWOTH)

See how:

See also: Write file with specific permissions in Python

查看更多
beautiful°
3楼-- · 2019-02-09 11:11

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+.

Option1:

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

Option2:

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).

查看更多
劳资没心,怎么记你
4楼-- · 2019-02-09 11:14

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(...)
查看更多
登录 后发表回答