title: Python: Moving files to folder based on filenames
body: <p>I have a folder with 10 images that I wish to move into a new folder based on it's current filenames. I've successfully been able to move every images in the folder into a new folder, and as of now I've been successful at moving each image filename to its own folder but I've yet to figure out how to move all images with the same filename into one folder and the other to another folder. For example below I want to move the images accordingly.</p>
  
  <ul>
  <li>1600_01.jpg ---> folder 1</li>
  <li>1700_01.jpg ---> folder 1</li>
  <li>1800_02.jpg ---> folder 2</li>
  <li>1900_02.jpg ---> folder 2</li>
  <li>2000_03.jpg ---> folder 3</li>
  <li>2100_03.jpg ---> folder 3</li>
  </ul>
  
  <p>This is my code thus far for moving the image files to a new folder by creating new folders based on it's filename. I got the part on making folders but I'm quite confused when it created separate image folders for all the images.</p>
  
  <pre><code>import os, shutil, glob
  
  #Source file 
  sourcefile = 'Desktop/00/'
  
  # for loop then I split the names of the image then making new folder 
  for file_path in glob.glob(os.path.join(sourcefile, '*.jpg*')):
      new_dir = file_path.rsplit('.', 1)[0]    
      # If folder does not exist try making new one
      try:
          os.mkdir(os.path.join(sourcefile, new_dir))
      # except error then pass
      except WindowsError:
          pass
      # Move the images from file to new folder based on image name
      shutil.move(file_path, os.path.join(new_dir, os.path.basename(file_path)))
  </code></pre>
  
  <p>This is what I got after I ran my script.
  <a href="https://i.stack.imgur.com/X2pLM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X2pLM.png" alt="This is what I got after I ran my script"></a></p>
  
  <p>However, What I'm trying to do is shown in this image below:
  <a href="https://i.stack.imgur.com/De0Kb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/De0Kb.png" alt="Goal"></a></p>