Change file to read-only mode in Python

I write data processing code in which I create a new file, write the processed data to this file and close it. But the file must be closed in read-only mode so that it is not accidentally modified. Can this be done in Python?

+7
python file-io
source share
2 answers

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) 

Please note that this assumes that you have the appropriate permissions and that you want the owner to be able to read this file. Remove S_IROTH and S_IRGRP if it is not.

UPDATE

If you need to write the file again, just call os.chmod as follows:

 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 

Just call this before you open the file for writing, then call the first form to make it read-only after you are done.

+11
source share

I think you could use the os module after writing to your file to change the file permissions as follows:

 import os filename=open("file_name","w") filename.write("my text") filename.close() os.system("chmod 444 file_name") 
-2
source share

All Articles