Make file read-only in Python

If you want to make file read-only:

import os
from stat import S_IREAD

os.chmod('path/to/file.txt', S_IREAD)


If you want to make file writeable:

import os
from stat import S_IWRITE

os.chmod('path/to/file.txt', S_IWRITE)


This snippet toggles a file between read-only and writable in Python using os.chmod with stat flags. Setting S_IREAD makes it read-only; S_IWRITE makes it writable again.

It is handy for protecting generated output or configuration from accidental edits. On Unix like systems the effect also depends on ownership and the existing permissions.

Comments

Popular posts from this blog

[Solved] Error: No such keg: /usr/local/Cellar/gcc

[How To] Unfollow Non-followers on Instagram