title: Moving files and creating directories if certain file type in python
body: <p>This is probably a simple question, but I'm brand new to python and programming in general. </p>
  
  <p>I'm working on a simple program to copy/move .mp3 files from on location to another while mirroring the directory structure of the source location. What I have so far works, however it also creates new folders in the destination location even if the source folder contained no mp3 files.  I only want to create the new directories if the source contains .mp3s, otherwise it could lead to a bunch of empty folders in the destination.</p>
  
  <p>Here is what I have so far:</p>
  
  <pre><code>import os
  import shutil #Used for copying files
  
  ##CONFIG
  source_dir = "C:\Users\username\Desktop\iTunes\\" #set the root folder that you want to     scan and move files from.  This script will scan recursively.
  destPath = "C:\Users\username\Desktop\converted From iTunes" #set the destination root that you want to move files to.  Any non-existing sub directories will be created.
  ext = ".mp3" #set the type of file you want to search for.
  count = 0 #initialize counter variable to count number of files moved
  ##
  
  ##FIND FILES
  for dirName, subdirList, fileList in os.walk(source_dir):
  
      #set the path for the destination folder(s)
      dest = destPath + dirName.replace(source_dir, '\\') 
  
      #if the source directory doesn't exist in the destination folder
      #then create a new folder
      if not os.path.isdir(dest):
          os.mkdir(dest)
          print('Directory created at: ' + dest)
  
      for fname in fileList:
          if fname.endswith(ext) :
              #determine source &amp; new file locations
              oldLoc = dirName + '\\' + fname
              newLoc = dest + '\\' + fname
  
              if os.path.isfile(newLoc): # check to see if the file already exists.  If it does print out a message saying so.
                  print ('file "' + newLoc + fname + '" already exists')
  
              if not os.path.isfile(newLoc): #if the file doesnt exist then copy it and print out confirmation that is was copied/moved
                  try:
                      shutil.move(oldLoc, newLoc)
                      print('File ' + fname + ' copied.')
                      count = count + 1
                  except IOError:
                      print('There was an error copying the file:  "' + fname + '"')
                      print 'error'            
  
  print "\n"
  print str(count) + " files were moved."
  print "\n"
  </code></pre>
  
  <p>so if the folder structure is something like:</p>
  
  <pre><code>root-&gt;
   band 1-&gt;
    album name-&gt;
     song.m4a,
     song2.m4a
  </code></pre>
  
  <p>right now it will create all those folders in the destination driectory, even though there are no .mp3s to copy.....</p>
  
  <p>Any help is appreciated!</p>