How to detect whether a file is readable and writable in Python?

Posted on In QA

Before reading or writing a file, access should be checked first. How to detect whether a file is readable and writable in Python?

You can use the

os.access(path, mode)

library function https://docs.python.org/release/2.6.6/library/os.html#os.access like the Linux access library function for C.

It returns True if access is allowed, False if not.

For readable and writable, you can test file path with mode set to:

os.R_OK

Value to include in the mode parameter of access() to test the readability of path.

os.W_OK

Value to include in the mode parameter of access() to test the writability of path.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *