Read filenames from CSV and then copy the files to different directory

筅森魡賤 提交于 2020-01-06 15:05:14

问题


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.


回答1:


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)



回答2:


Adding to Daniel's post, since he did warn he hadn't tested it :), I think you'll need to make a couple small changes. Basically, I think the issue in the suggested code is that filename is assumed to be the full path. But then that creates a problem when you get to the os.path.join command for new_filename because you're adding a new path to a full path and name.

I would suggest including a filepath and filename in your csv to make the code run. The changes appear to work when I testd it, although I didn't run as a function (and I used print() statements for Python 3.4 syntax):

with open(csv_file, 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
      # Assuming the columns in the CSV file we want are the first two  // Changed
      filename = row[0]
      filepath = row[1]   #Changed

     '''Changed: I skipped over this next part, didn't need it, but should be
     easy enough to figure out
     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...' % filepath, new_filename)  #Changed
     shutil.copy(filepath, new_filename)   #Changed
     print 'done.'
print 'All done!'


来源:https://stackoverflow.com/questions/29850220/read-filenames-from-csv-and-then-copy-the-files-to-different-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!