title: Python Move Files Based On Name
body: <p>To give credit, the code I am currently working with is from this response by <strong>cji</strong>, <a href="https://stackoverflow.com/questions/13446857/how-to-match-and-move-files-into-corresponding-folders-using-python">here.</a></p>
  
  <p>I am trying to recursively pull all files from the source folder, and move them into folders from the file names first-five characters <code>0:5</code></p>
  
  <p>My Code Below:</p>
  
  <pre><code>import os
  import shutil
  
  srcpath = "SOURCE"
  srcfiles = os.listdir(srcpath)
  
  destpath = "DESTINATION"
  
  # extract the three letters from filenames and filter out duplicates
  destdirs = list(set([filename[0:5] for filename in srcfiles]))
  
  
  def create(dirname, destpath):
      full_path = os.path.join(destpath, dirname)
      os.mkdir(full_path)
      return full_path
  
  def move(filename, dirpath):
      shutil.move(os.path.join(srcpath, filename)
                  ,dirpath)
  
  # create destination directories and store their names along with full paths
  targets = [(folder, create(folder, destpath)) for folder in destdirs]
  
  for dirname, full_path in targets:
      for filename in srcfiles:
          if dirname == filename[0:5]:
              move(filename, full_path)
  </code></pre>
  
  <p>Now, changing <code>srcfiles = os.listdir(srcpath)</code> and <code>destdirs = list(set([filename[0:5] for filename in srcfiles]))</code> <strong>with the code below</strong> gets me the paths in one variable and the first five characters of the file names in another.</p>
  
  <pre><code>srcfiles = []
  destdirs = []
  
  for root, subFolders, files in os.walk(srcpath):
      for file in files:
         srcfiles.append(os.path.join(root,file))
      for name in files:
         destdirs.append(list(set([name[0:5] for file in srcfiles])))
  </code></pre>
  
  <p>How would I go about modifying the original code to use this... Or if someone has a better idea on how I would go about doing this. Thanks.</p>