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

Cách kiểm tra quyền thư mục bằng Python?


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

>>> import os
>>> os.access('my_folder', os.R_OK)  # Check read access
True
>>> os.access('my_folder', os.W_OK)  # Check write access
True
>>> os.access('my_folder', os.X_OK)  # Check execute access
True
>>> os.access('my_folder', os.X_OK | os.W_OK)  # Check write file to dir
True

Cũng theo idiom Python: Easier to ask forgiveness than permission. Thử ghi vào thư mục, bắt lỗi nếu không có quyền.