问题
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