Python function chmod to change permission

I naively tried the function chmod from the standard python module called os to change the permission of a file:

os.chmod(filename, 644)

Checking in the unix command line (ls -l), I got an unexpected result:

--w----r-T.

I expected indeed a read-write permission and then 2 read-only. In Python 2.X, you must set the second argument (the mode) to 0644 (note the 0)

os.chmod(filename, 0644)

In Python 3.X, this statement becomes:

os.chmod(filename, 0o644)

and now, we get the expected answer.

-rw-r--r--.

Therefore the mode should be in octal form!! Not obvious from the documentation:

In [5]: os.chmod?
Type:       builtin_function_or_method
String Form:<built-in function chmod>
Docstring:
chmod(path, mode)
 
Change the access permissions of a file.
Please follow and like us:
This entry was posted in Python and tagged . Bookmark the permalink.

2 Responses to Python function chmod to change permission

Leave a Reply

Your email address will not be published. Required fields are marked *