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

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

asked Oct 3, 2016 by anonymous

1 Answer

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.
answered Oct 8, 2016 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...