Permission problems when creating a dir with os.makedirs in Python

Question:

I’m simply trying to handle an uploaded file and write it in a working dir which name is the system timestamp. The problem is that I want to create that directory with full permission (777) but I can’t! Using the following piece of code the created directory with 755 permissions.

def handle_uploaded_file(upfile, cTimeStamp):
    target_dir = "path_to_my_working_dir/tmp_files/%s" % (cTimeStamp)
    os.makedirs(target_dir, mode=0777)
Asked By: green69

||

Answers:

According to the official python documentation the mode argument of the os.makedirs function may be ignored on some systems, and on systems where it is not ignored the current umask value is masked out.

Either way, you can force the mode to 0o777 (0777 threw up a syntax error) using the os.chmod function.

Answered By: srgerg

For Unix systems (when the mode is not ignored) the provided mode is first masked with umask of current user. You could also fix the umask of the user that runs this code. Then you will not have to call os.chmod() method.
Please note, that if you don’t fix umask and create more than one directory with os.makedirs method, you will have to identify created folders and apply os.chmod on them.

For me I created the following function:

def supermakedirs(path, mode):
    if not path or os.path.exists(path):
        return []
    (head, tail) = os.path.split(path)
    res = supermakedirs(head, mode)
    os.mkdir(path)
    os.chmod(path, mode)
    res += [path]
    return res
Answered By: user2120286

You are running into problems because os.makedir() honors the umask of current process (see the docs, here). If you want to ignore the umask, you’ll have to do something like the following:

import os
try:
    original_umask = os.umask(0)
    os.makedirs('full/path/to/new/directory', desired_permission)
finally:
    os.umask(original_umask)

In your case, you’ll want to desired_permission to be 0777 (octal, not string). Most other users would probably want 0755 or 0770.

Answered By: dbn

The other anwsers did not worked for me (with python 2.7).

I had to add os.umask(0) before, to remove the mask for the current user. And I had to change the mode from 0777 to 0o777:

def handle_uploaded_file(upfile, cTimeStamp):
    target_dir = "path_to_my_working_dir/tmp_files/%s" % (cTimeStamp)
    os.umask(0)
    os.makedirs(path, mode=0o777)
Answered By: veben
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.