1

I'm using the following code to create a directory (if it doesn't exist) and a file inside that directory:

import os

mystr = 'hello world!'
mypath = '/salam/me/'

if not os.path.exists(mypath):
    oldmask = os.umask(000)
    os.makedirs(mypath, 0755)
    os.umask(oldmask)

text_file = open(mypath + "myfile", "w")
text_file.write("%s" % mystr)
text_file.close()

But I get IOError: [Errno 13] Permission denied from the console. I followed answers to other similar questions and they suggested unmasking and using 0755/0o755/0777/0o777

But they don't seem to work in this case. What am I doing wrong?

Follow up question: I want to do this job in /var/lib/. Is it going to be different? (in terms of setting up the permission)

NOTE This is Python version 2.7

4

1 回答 1

3

您需要以 root 身份运行脚本,因为父文件夹/var/lib归 root 所有。不需要 umask 命令。

除此之外,我会像这样重写代码以避免竞争条件:

#!/usr/bin/env python3
import os

mystr = 'hello world!'
mypath = '/salam/me/'

try:
    os.makedirs(mypath, 0755)
except FileExistsError:
    print('folder exists')

text_file = open(mypath + "myfile", "w")
text_file.write("%s" % mystr)
text_file.close()

然后以root身份运行脚本:

sudo python3 my_script.py

PS:如果绑定的是Python 2,则需要在上述解决方案中替换FileExistsError为。OSError但是您必须另外检查errno

#!/usr/bin/env python2
import errno
import os

mystr = 'hello world!'
mypath = '/salam/me/'

try:
    os.makedirs(mypath, 0755)
except OSError as e:
    if e.errno == errno.EEXIST:
        print('folder exists')
    else:
        raise

text_file = open(mypath + "myfile", "w")
text_file.write("%s" % mystr)
text_file.close()
于 2019-05-17T20:53:56.363 回答