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/libis owned by root. The umask commands aren't needed.Besides that, I would rewrite the code like this to avoid a race condition:
Then run the script as root:
PS: If you are bound to Python 2, you need to replace
FileExistsErrorbyOSErrorin the above solution. But you have to additionally checkerrno: