Change file to read-only mode in Python

For this you use os.chmod

import os
from stat import S_IREAD, S_IRGRP, S_IROTH

filename = "path/to/file"
os.chmod(filename, S_IREAD|S_IRGRP|S_IROTH)

Note that this assumes you have appropriate permissions, and that you want more than just the owner to be able to read the file. Remove S_IROTH and S_IRGRP as appropriate if that’s not the case.

UPDATE

If you need to make the file writable again, simply call os.chmod as so:

from stat import S_IWUSR # Need to add this import to the ones above

os.chmod(filename, S_IWUSR|S_IREAD) # This makes the file read/write for the owner

Simply call this before you open the file for writing, then call the first form to make it read-only again after you’re done.

Leave a Comment