Created
June 21, 2018 16:15
-
-
Save aflansburg/49b4665c724af5b0cd4dc9057049a751 to your computer and use it in GitHub Desktop.
Traverse (walk) a directory tree, match filenames provided in csv, copy matched file to another directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import shutil | |
import csv | |
# to store filenames provided in csv | |
filenames = [] | |
# read single column csv of filenames (no extension) | |
csv_path = 'parts.csv' | |
with open(csv_path, newline='') as csvfile: | |
filenameRdr = csv.reader(csvfile, delimiter=',') | |
for row in filenameRdr: | |
print('appending filename', row[0]) | |
filenames.append(row[0] + '.pdf') | |
print('list of filenames from csv %s' % filenames) | |
# base directory to copy from | |
base_dir = os.path.normpath("C:/some_directory") | |
# directory to copy to | |
copy_dir = os.path.normpath("C:/some_new_directory") | |
# to store failures (non match filenames from csv) | |
failures = [] | |
# to store filenames found in the base_dir | |
jfilelist = [] | |
print('writing files') | |
# walk traverses the directory's entire structure | |
for root, dirs, files in os.walk(base_dir): | |
# append all filenames found in base_dir to list | |
for f in files: | |
jfilelist.append(f) | |
# try copying the file | |
if f in filenames: | |
try: | |
print('writing %s to tyler_temp directory' % os.path.join(root, f)) | |
shutil.copy(os.path.join(root, f), copy_dir) | |
except: | |
pass # handle error here | |
# this is where we log the failures | |
for fn in filenames: | |
if fn not in jfilelist: | |
failures.append(fn) | |
# write the failures to txt file | |
with open(os.path.normpath("J:/Instructions/tyler_temp/failures.txt"), "w") as failFile: | |
for fail in failures: | |
failFile.write('\n%s' % fail) | |
print('these items failed: %s' % failures) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment