I need to write into several files that usually needs higher level permission than a regular user. Before doing anything, I would like the check if the current user can write in all of them. If so, proceed to writing. Otherwise warns the user and asks to check first the user level permission.
In nix systems, like Linux and Mac OS, I can rely on os.access
, but it seems that simply does not work on Windows. It tells that the file always have write permission, but proceeding to the writing I stumble in an unexpected exception of PermissionError - Permission denied.
I saw the StackOverflow link pointing to the win32security (Checking folder/file ntfs permissions using python). But the topic is 10 years old, and checking for library today, it doesn't seems that library is currently supported or mantained.
Snippet to check permission:
import os
if os.name == 'posix':
file_to_write = '/etc/hosts'
else:
file_to_write = 'C:\\Windows\\System32\\drivers\\etc\\hosts'
if os.access(file_to_write, os.W_OK):
print("I can write in!")
else:
print("Can't write. No permission.")
Then, the code to write in the file:
import os
if os.name == 'posix':
file_to_write = '/etc/hosts'
else:
file_to_write = 'C:\\Windows\\System32\\drivers\\etc\\hosts'
file_resource = open(file_to_write, 'a')
file_resource.write("\ntest")
file_resource.close()
Testing my snippets, using python3, in any operational system, or even testing any file in the system (not necessarily the hosts file in my example), python shall tells previously if the file can be written by the current user. If so, then the second snippet must not return an exception of PermissionError - Permission denied, and the target file shall have a word "test" in the file's last line. Otherwise, I won't even try the second snippet. In Windows environment, python dumbly tells that any existing file have write permission.