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
I ran into this same need while adding an argument via argparse. The built in
type=FileType('w')
wouldn't work for me as I was looking for a directory. I ended up writing my own method to solve my problem. Here is the result with argparse snippet.That results in the following:
I went back and added print opts.dir to the end, and everything appears to be functioning as desired.
more info about access can be find it here
If you need to check the permission of another user (yes, I realize this contradicts the question, but may come in handy for someone), you can do it through the
pwd
module, and the directory's mode bits.Disclaimer - does not work on Windows, as it doesn't use the POSIX permissions model (and the
pwd
module is not available there), e.g. - solution only for *nix systems.Note that a directory has to have all the 3 bits set - Read, Write and eXecute.
Ok, R is not an absolute must, but w/o it you cannot list the entries in the directory (so you have to know their names). Execute on the other hand is absolutely needed - w/o it the user cannot read the file's inodes; so even having W, without X files cannot be created or modified. More detailed explanation at this link.
Finally, the modes are available in the
stat
module, their descriptions are in inode(7) man.Sample code how to check:
Stumbled across this thread searching for examples for someone. First result on Google, congrats!
People talk about the Pythonic way of doing it in this thread, but no simple code examples? Here you go, for anyone else who stumbles in:
This attempts to open a filehandle for writing, and exits with an error if the file specified cannot be written to: This is far easier to read, and is a much better way of doing it rather than doing prechecks on the file path or the directory, as it avoids race conditions; cases where the file becomes unwriteable between the time you run the precheck, and when you actually attempt to write to the file.
It may seem strange to suggest this, but a common Python idiom is
Following that idiom, one might say:
Try writing to the directory in question, and catch the error if you don't have the permission to do so.
Check the mode bits: