Read filenames from CSV and then copy the files to different directory
Question: I have been able to write a batch file to find files and put the file paths
into a CSV. I haven't been able to figure out how to read the file locations
from the CSV and then move the files to a different storage device with the
same folder structure using python. This is what I'd like to do.

I wish I had some code to show you but none of it has worked.


Answer: Here's a quick and dirty solution. (I haven't tested it yet, YMMV!)

    
    
    import csv
    import os
    import shutil
    import sys
    
    
    def main(argv):
      # TODO: this should do some error checking or maybe use optparse
      csv_file, existing_path_prefix, new_path_prefix = argv[1:]
    
      with open(csv_file, 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
          # Assuming the column in the CSV file we want is the first one
          filename = row[0]
    
          if filename.startswith(existing_path_prefix):
            filename = filename[len(existing_path_prefix):]
    
          new_filename = os.path.join(new_path_prefix, filename)
    
          print ('Copying %s to %s...' % filename, new_filename),
          shutil.copy(filename, new_filename)
          print 'done.'
      print 'All done!'
    
    
    if __name__ == '__main__':
      main(sys.argv)
    

