Determining Whether a Directory is Writeable

前端 未结 10 1930
萌比男神i
萌比男神i 2020-12-07 14:44

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 sh

10条回答
  •  悲&欢浪女
    2020-12-07 15:07

    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.

    #! /usr/bin/env python
    import os
    import argparse
    
    def writable_dir(dir):
        if os.access(dir, os.W_OK) and os.path.isdir(dir):
            return os.path.abspath(dir)
        else:
            raise argparse.ArgumentTypeError(dir + " is not writable or does not exist.")
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-d","--dir", type=writable_dir(), default='/tmp/',
        help="Directory to use. Default: /tmp")
    opts = parser.parse_args()
    

    That results in the following:

    $ python dir-test.py -h
    usage: dir-test.py [-h] [-d DIR]
    
    optional arguments:
      -h, --help         show this help message and exit
      -d DIR, --dir DIR  Directory to use. Default: /tmp
    
    $ python dir-test.py -d /not/real
    usage: dir-test.py [-h] [-d DIR]
    dir-test.py: error: argument -d/--dir: /not/real is not writable or does not exist.
    
    $ python dir-test.py -d ~
    

    I went back and added print opts.dir to the end, and everything appears to be functioning as desired.

提交回复
热议问题