I try to set file access rights in Python in os.chmod
in Windows.
I can succeed removing write access, but not read access:
>>> import os
>>> import stat
>>> from pathlib import Path
>>> toto = Path("toto.txt")
>>> toto.write_text("Hello")
5
>>> toto.read_text()
'Hello'
>>> os.chmod(toto, toto.stat().st_mode & ~stat.S_IWUSR)
>>> toto.write_text("Hello")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\python37-32\lib\pathlib.py", line 1208, in write_text
with self.open(mode='w', encoding=encoding, errors=errors) as f:
File "c:\python37-32\lib\pathlib.py", line 1176, in open
opener=self._opener)
File "c:\python37-32\lib\pathlib.py", line 1030, in _opener
return self._accessor.open(self, flags, mode)
PermissionError: [Errno 13] Permission denied: 'toto.txt'
[Errno 13] Permission denied: 'toto.txt'
>>> os.chmod(toto, stat.S_IRWXU)
>>> toto.write_text("Hello")
5
>>> os.chmod(toto, toto.stat().st_mode & ~stat.S_IRUSR)
>>> toto.read_text()
'Hello'
The last line should have raised an error because the file should have no rights to be read.
How to solve the issue?