使用os创建文件夹和子文件夹。代码改进

时间:2019-02-19 13:36:51

标签: python operating-system directory subdirectory

我想自动化当前正在处理的某些东西。目前,我正在编写一个函数,该函数会自动为我创建所有目录和子目录。我觉得这是硬编码的。.如果有人可以看看并告诉我可以在哪里以及如何改进我的代码,我将不胜感激。

谢谢!

def create_dirs(MD,home_team,away_team,info):
    folders = ["Stats","Press","Info"]
    gamefolder = (home_team+" vs "+away_team+" ("+info+")")
    infofolder = ("Info-Pictures "+"("+info+")")
    path = (r"C:\path\to\destination\")
    newpath =(r"C:\path\to\destination\\"+MD)
    gamedir = (r"C:\path\to\destination\\"+MD+r"\\"+gamefolder)
    infodir = (r"C:\path\to\destination\\"+MD+r"\\"+infofolder)

    try:
        os.chdir(path)
        if not os.path.exists(MD):
            os.makedirs(MD)
    except OSError:
        print('Error: Creating directory:' + MD)
    try:
        os.chdir(newpath)
        os.mkdir(gamefolder)
        os.mkdir(infofolder)
    except OSError:
        print('Error: Creating directory:' + gamefolder)
    try:
        for folder in folders:
            os.mkdir(os.path.join(gamefolder,folder))
    except OSError:
        print('Error: Creating directory. Directory/ies already exists')
    try:
        os.chdir(infodir)
        os.mkdir("Before")
        os.mkdir("After")
    except OSError:
        print('Error: Creating directory. Directory/ies already exist')

1 个答案:

答案 0 :(得分:0)

只需使用os.makedirs:

import os
os.makedirs("C:\\Users\\<username>\\Desktop\\asd\\asd\\asd\\asd")

它将创建一个文件夹和子文件夹