Python中的递归目录创建

时间:2017-10-26 10:14:37

标签: python python-2.7 recursion

我正在使用Python 2.7,使用它来编写环境设置脚本。我正在向我的脚本提供一个文本文件,其中包含应检查的目录列表,如果它们不存在则创建。

我有主要机制,但是当我创建不存在的目录时,似乎有一种奇怪的行为。这段代码是:

def checkPaths(fileArray):
#fileArray is an array of file paths as strings
    for item in fileArray:
        print item
        if os.path.exists(item):
            print '\t path exists for item'
        else:
            response = raw_input('\t path does not exist for item. \n\tDo you want to create it? [y/n]: ')
            type(response.lower())
            if response == 'y':
                print 'Making new dir'
                parseAndBuildPath(item)
            elif response == 'n':
                print 'Not making new dir'
                continue
            else:
                print 'Response not recognised'
                exit(0)

def parseAndBuildPath(filePath):
    splitFilePath = filePath.split(_SEPARATOR)
    #Find out which parts of the supplied path don't exist and create them...
    recursiveFileCheck(splitFilePath, 0, '')
    return

def recursiveFileCheck(splitFilePath, arrayIndex, currentState):
print ''
if arrayIndex < len(splitFilePath):
    #Follow on from parseAndBuildPath, recursively check the split path. If it doesn't exist, create it and iterate
    #Split file path is an array, arrayIndex is int

    #Check the current state of recursion
    if currentState == '':
        #For the first iteration, don't add a separator
        currentState = currentState+splitFilePath[arrayIndex]
    else:
        #All other times, add the separator
        currentState = currentState+_SEPARATOR+splitFilePath[arrayIndex]

    if not os.path.exists(currentState):
            print 'Current state before creation is '+currentState
            os.makedirs(os.path.dirname(currentState))
    else:
        print currentState + " exists. Not creating new dir..."

    arrayIndex = arrayIndex+1
    recursiveFileCheck(splitFilePath, arrayIndex, currentState)
else:
    print "Finished recursive check. Returning."
    return

如您所见,我的if语句正在检测currentState(文件路径)是否存在。如果没有,它会尝试创建目录。每次运行时,它都会遇到异常,说路径已经存在,但是会阻止一个目录远离目标目录。例如

Checking for C:\Users\Donglecow\Documents\Python\FOO\BAR\
     path does not exist for item. 
Do you want to create it? [y/n]: y
Making new dir
Skipping creation of C:\Users\Donglecow\Documents\Python\FOO because it already exists. 

当检测到目录不存在时,它在创建目录时失败,因为其中一个父目录存在,但currentState变量是准确的。

Current state before creation is C:\Users\Jacob\Documents\Python\FOO
...
WindowsError: [Error 183] Cannot create a file when that file already exists: 'C:\\Users\\Donglecow\\Documents\\Python'

0 个答案:

没有答案