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

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)

Solution 1:

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.

Solution 2:

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.

Solution 3:

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