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
You need to run the script as root because the parent folder /var/lib
is owned by root. The umask commands aren't needed.
Besides that, I would rewrite the code like this to avoid a race condition:
#!/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()
Then run the script as root:
sudo python3 my_script.py
PS: If you are bound to Python 2, you need to replace FileExistsError
by OSError
in the above solution. But you have to additionally check 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()