尝试使用 makedirs python 复制文件时出现 FileExistsError 3

FileExistsError when trying to copy files with makedirs python 3

所以我是 运行 这个代码,它从一个文件夹中获取文件并将它们复制到另一个目录中。然而,当我尝试创建新的目录树时,我得到了一个 FileExistsError,即使我没有在代码的其他任何地方创建该目录树。有什么问题吗?

import os
import shutil
import datetime

class CopyFilesModuleTest:

    def __init__(self):
        self.folderName = ""
        self.timeName = CopyFilesModuleTest.formatTimeStr(datetime.datetime.now())

    def getDirFiles(self):
        src_files = os.listdir(self.folderName)
        return src_files

    def copyFiles(self,src_files):
        for file_name in src_files:
            full_file_name = self.folderName+"/"+file_name
            if(os.path.isfile(full_file_name)):
                destPath = self.getNewFileDest(file_name)
                destDir = self.getNewFileDir()
                self.createDirectory(destDir)
                shutil.copy(full_file_name,destPath)

    def getNewFileDest(self,fileName):
        mainFold = "userDataBackUp"
        full_File_Path = mainFold+"/"+self.timeName+"/"+self.folderName+"/"+fileName
        return full_File_Path

    def getNewFileDir(self):
        mainFold = "userDataBackUp"
        full_File_Dir = mainFold+"/"+self.timeName+"/"+self.folderName
        return full_File_Dir

    @staticmethod
    def formatTimeStr(tStr):
        tStr = str(tStr)
        colon = ":"
        space = " "
        dot = "."
        bLine = "-"
        tStr = tStr.replace(colon,"_")
        tStr = tStr.replace(space,"_")
        tStr = tStr.replace(dot,"_")
        tStr = tStr.replace(bLine,"_")
        return tStr

    def createDirectory(self,filePath):
        os.makedirs(filePath)

    def copyAllFromFolder(self,fName):
        self.folderName = fName
        src_files1 = cfm1.getDirFiles()
        cfm1.copyFiles(src_files1)



cfm1 = CopyFilesModuleTest()
cfm1.copyAllFromFolder("folder_files")

该目录可能已经存在。在这种情况下,os.makedirs 会引发 FileExistsError(这就是我的 python 3.5 解释器所做的;3.6 文档说它会引发 OSError)。这应该是诀窍:

os.makedirs(filePath, exist_ok=True)

(如 os.makedirs 的文档中所述)。