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.
1 Answer
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."
os.access(filename, os.W_OK)
. This should account for both file permissions and file attributes (e.g. immutability). In Windows,os.access
only checks the readonly file attribute. The simplest way to check for write permission in Windows is to open the file viaCreateFileW
(via ctypes or PyWin32's win32file), requesting generic write access and sharing read, write, and delete access.root
user regardless of readonly flag on the file -- refer to unix.stackexchange.com/q/412234/296692