简体   繁体   中英

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]<\/code> 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.

"

statinfo = os.stat(path, *, dir_fd=None, follow_symlinks=True)

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}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM