50
votes

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)
4
What is the error you are getting? - Ikke
I simply get the directory but with the wrong permissions (755 instead of 777). - green69
Whatever it is you are hoping to accomplsh, chmod 0777 is wrong and insecure and you should revert to sane permissions immediately, or in the worst case reinstall your system if you cannot be sure that users who should not be able to overwrite system files haven't abused the security hole you created. - tripleee

4 Answers

40
votes

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.

36
votes

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.

14
votes

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
0
votes

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)