美文网首页
python当目录不存在时创建create_dir_if_not

python当目录不存在时创建create_dir_if_not

作者: 洛丽塔的云裳 | 来源:发表于2019-10-13 15:31 被阅读0次
    方法1:参照argparse模块,实现当目录不存在时创建
    #-*- coding: utf-8 -*-
    import os
    import argparse
    
    def create_dir_if_not_there(path, dir_name):
        """ Checks to see if a directory exists in the users home directory, if not then create it. """
        if not os.path.exists(dir_name):
            os.mkdir(os.path.join(path, dir_name))
    
    def get_parser():
        """" get parser """
        current_path = os.getcwd()
        parser = argparse.ArgumentParser(description='create dir if not there')
        parser.add_argument('-path', '--p', default=current_path) # default 默认为当前路径
        parser.add_argument('-dirname', '--d', default='test')
        args = parser.parse_args()
        path = args.p
        dir_name = args.d
        return path, dir_name
    
    
    def main():
        """ main func """
        path, dir_name = get_parser()
        create_dir_if_not_there(path, dir_name)
    
    
    if __name__ == '__main__':
        main()
    

    测试结果
    测试case1:


    test1.png

    测试case2:


    test2.png
    测试case3:采用argparse默认path,默认目录名,同样可以创建目录
    test3.png
    注:方法1中的os.mkdir只能创建最后一级目录,。os.makedirs可以递归创建目录。具体参照github,如下:

    https://github.com/geekcomputers/Python/blob/master/create_dir_if_not_there.py

    os.path.expanduser('~')表示用户主目录。参见:https://docs.python.org/2.7/library/os.path.html?highlight=expanduser#os.path.expanduser

    #-*- coding: utf-8 -*-
    import os
    
    def create_dir_if_not_there(dir):
        """ Checks to see if a directory exists in the users home directory, if not then create it. """
        try:
            rootpath = os.path.expanduser('~')
            if not os.path.exists(os.path.join(rootpath, dir)):
                os.makedirs(os.path.join(rootpath, dir))
        except Exception as e:
            print e
    
    def main():
        """ main func """
        create_dir_if_not_there('hello/world/test.py')
    
    
    if __name__ == '__main__':
        main()
    

    测试结果:


    test4.png

    相关文章

      网友评论

          本文标题:python当目录不存在时创建create_dir_if_not

          本文链接:https://www.haomeiwen.com/subject/chqqmctx.html