python-os創建文件夾-create_dir_if_not_exist.py


#!/bin/usr/env python3

__author__ = 'nxz'

import os
import argparse

MESSAGE = '%s 文件夾已經存在'

def create_dir(work_dir, createdir):
    try:
        for dir in createdir:
            if not os.path.exists(os.path.join(work_dir, dir)):
                os.makedirs(os.path.join(work_dir, dir))
                print("%s 文件夾創建成功" % dir)
            else:
                print(MESSAGE % dir)
    except Exception as e:
        print(e)

def get_parser():
    parser = argparse.ArgumentParser(description='如果指定路徑下文件夾不存在,則創建')
    parser.add_argument('work_dir', metavar='WORK_DIR', nargs=1, type=str, help='指定文件夾')
    parser.add_argument('create_dir', metavar='CREATE_DIR', nargs='+', type=str, help='要創建的文件夾')
    return parser

def main():
    args = vars(get_parser().parse_args())
    work_dir = args['work_dir'][0]
    dir = args['create_dir']
    create_dir(work_dir, dir)

if __name__ == '__main__':
    main()

執行:python create_dir_if_not_exist.py C:\Users\nxz\Desktop\123 1111 2222


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM