How do i determine if a file is read only
I'm writing a shell in python and need to determine if a file is read only for the current user. How do i interpret os.stat(path)[0]
for a given user.
This isn't trivial on linux you may get write permissions because of user group or others. Then there's the concept of a user being in the files group with group write but is the owner with read only permissions.
I need this to be cross platform so it works on Mac Linux and Windows.
Solution 1:
statinfo = os.stat(path, *, dir_fd=None, follow_symlinks=True)
Here's a description from the documentation: https://docs.python.org/3/library/os.html#os.stat
"Get the status of a file or a file descriptor. Perform the equivalent of a stat() system call on the given path. path may be specified as either a string or bytes – directly or indirectly through the PathLike interface – or as an open file descriptor. Return a stat_result object."
Solution 2:
For those on Windows that stumbled upon this comment looking on how to check if a file is read only, here's my solution, tested on Python 3.7.9:
FILE_PATH = r"C:\temp\file.txt"
def is_file_read_only(path: str) -> bool:
try:
open(path, "w")
except PermissionError:
return True
else:
return False
read_only = is_file_read_only(FILE_PATH)
print(f'File is read only: {read_only}')