I am writing a data processing code, in which I create a new file, write processed data in to this file and close. But the file has to be closed in read-only mode, so that it would not be accidentally modified. Can this be done in Python?
5 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)
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.

- 8,875
- 2
- 30
- 37
-
And how do I change it to write when I run the program. I want to change it to write when the program runs and when it exits it should be changed to read-only mode. – Feb 13 '15 at 05:56
-
1Ah, you didn't specify that in the original question. I'll update – aruisdante Feb 13 '15 at 06:11
-
Does not work on Windows. Even if this article says it should https://docs.python.org/2/library/os.html#os.chmod – Shtefan Apr 09 '23 at 05:25
This solution preserves previous permission of the file, acting like command chmod -w FILE
import os
import stat
filename = "path/to/file"
mode = os.stat(filename).st_mode
ro_mask = 0o777 ^ (stat.S_IWRITE | stat.S_IWGRP | stat.S_IWOTH)
os.chmod(filename, mode & ro_mask)

- 11,620
- 5
- 64
- 44

- 126
- 1
- 5
Using pathlib.Path
, for modern python3, use path.chmod(mode: int)
The octal mode could be specified like 0o444
(read only). See this for more chmod mode options.
Note, if it is to apply to the symlink itself, see path.lchmod
.
For path.chmod
, after 3.10, there's now a follow_symlinks = True
parameter as well.
On windows, this may not be sufficient for anything but twiddling the read-only flag. See other SO posts [1].

- 1,120
- 1
- 7
- 17
For Windows OS maybe to try something like this:
import os
filename = open("file_name.txt", "w")
filename.write("my text")
filename.close()
os.system("attrib +r file_name.txt")
-
Not recommended because it is not operating system independent, and because it fails if file_name has a space in it. – vy32 May 19 '19 at 23:12
-
This seems to be the same as @dgsleeps answer that was posted 3 years earlier – General4077 Sep 07 '21 at 14:25
I guess you could use os module after writing on your file to change the file permissions like this:
import os
filename=open("file_name","w")
filename.write("my text")
filename.close()
os.system("chmod 444 file_name")

- 700
- 6
- 7
-
6calling chmod via `os.system` isn't portable, it won't work on windows. Better to use the `os.chmod` method directly. – aruisdante Feb 13 '15 at 05:08