Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
So I am running this code which takes files from a folder and copies them into another directory. However I get a FileExistsError when i try to make the new directory tree even though I don't create that directory tree anywhere else in the code. What can be wrong?
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")
the directory probably already exists. os.makedirs
will raise a FileExistsError
in this case (that's what my python 3.5 interpreter does; the 3.6 doc says it will raise an OSError
). this should to the trick:
os.makedirs(filePath, exist_ok=True)
(as in the doc of os.makedirs
).
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.