Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách kiểm tra quyền file bằng Python?


Dùng os.access(path, mode) kiểm tra permission file với mode đọc, ghi, thực thi. Ví dụ:

>>> import os
>>> os.access('my_file', os.R_OK)  # Check read access
True
>>> os.access('my_file', os.W_OK)  # Check write access
True
>>> os.access('my_file', os.X_OK)  # Check execute access
False
>>> os.access('my_file', os.F_OK)  # Check existence
True

Cũng dùng os.stat lấy status file/file descriptor. Phức tạp vì dùng bitmask. Xem: https://docs.python.org/3/library/os.html#os.stat