What would be the best way in Python to determine whether a directory is writeable for the user executing the script? Since this will likely involve using the os module I should mention I'm running it under a *nix environment.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
My solution using the
tempfile
module:If you only care about the file perms,
os.access(path, os.W_OK)
should do what you ask for. If you instead want to know whether you can write to the directory,open()
a test file for writing (it shouldn't exist beforehand), catch and examine anyIOError
, and clean up the test file afterwards.More generally, to avoid TOCTOU attacks (only a problem if your script runs with elevated privileges -- suid or cgi or so), you shouldn't really trust these ahead-of-time tests, but drop privs, do the
open()
, and expect theIOError
.Although what Christophe suggested is a more Pythonic solution, the os module does have the os.access function to check access:
os.access('/path/to/folder', os.W_OK)
# W_OK is for writing, R_OK for reading, etc.Here is something I created based on ChristopheD's answer: