title: Python - How to handle folder creation if folder already exists
body: <p>def copy_excel():</p>
  
  <pre><code>    srcpath = "C:\\Aloha"           #where the excel files are located
      srcfiles = os.listdir(srcpath)  #sets srcfiles as list of file names in the source path folder
      destpath = "C:\\"               #destination where the folders will be created
      destdir = list(set([filename[19:22] for filename in srcfiles])) #extract three digits from filename to use for folder creation (i.e 505, 508, 517,...)
  
      #function to handle folder creation
      def create(dirname, destpath):
              full_path = os.path.join(destpath, dirname)
              if os.path.exists(full_path):
                      pass
              else:
                      os.mkdir(full_path)
              return full_path
  
      #function to handle moving files to appropriate folders
      def move(filename, dirpath):
              shutil.move(os.path.join(srcpath, filename), dirpath)
  
      #creates the folders with three digits as folder name by calling the create function above
      targets = [(folder, create(folder, destpath)) for folder in destdir]
      #handles moving files to appropriate folders if the three digits in file name matches the created folder
      for dirname, full_path in targets:
              for filename in srcfiles:
                      if dirname == filename[19:22]:
                              move(filename, full_path)
                      else:
                              pass
  </code></pre>
  
  <p>I am somewhat new to Python so please bear with me! I was able to find this code block on this site and tailored it to my specific use case. The code works well for creating the specified folders and dropping the files into the corresponding folders. However, when I run the code again for new files that are dropped into the <code>"C:\\Aloha"</code> I get a <code>Error 183: Cannot create a file when that file already exists.</code> In this case, the folder already exists because it was previously created when the script was run the first time.</p>
  
  <p>The code errors out when targets attempts to create folders that already exist. My question is, what is the logic to handle folders that already exists and to ignore the error and just move the files to the corresponding folders? The script should only create folders if they are not already there.</p>
  
  <p>Any help would be greatly appreciated! I have attempted try/except and nesting if/else statements as well as <code>os.path.isdir(path)</code> to check to see if the directory exists but I haven't had any luck. I apologize for any of the comments that are wrong, I am still learning Python logic as I build this script out.</p>