From 017da396119f622fe759e9f7389f7842c7dc590a Mon Sep 17 00:00:00 2001 From: mjanowiecki <32551917+mjanowiecki@users.noreply.github.com> Date: Wed, 14 Nov 2018 14:38:02 -0500 Subject: [PATCH] Update renameDirectories.py Added argparse, changed topdown=false, added time --- renameDirectories.py | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/renameDirectories.py b/renameDirectories.py index e5acc5b..4e9a8f5 100644 --- a/renameDirectories.py +++ b/renameDirectories.py @@ -1,14 +1,36 @@ import os import csv from datetime import datetime +import time +import argparse -filePath = raw_input('Enter file path (C:/Test/): ') +parser = argparse.ArgumentParser() +parser.add_argument('-d', '--directory', help='the file path of name changes. optional - if not provided, the script will ask for input') +parser.add_argument('-f', '--fileNameCSV', help='the CSV file of name changes. optional - if not provided, the script will ask for input') +parser.add_argument('-m', '--makeChanges', help='Enter "true" to if the script should actually rename the files (otherwise, it will only create a log of the expected file name changes). optional - if not provided, the script will to "false"') +args = parser.parse_args() +if args.directory: + directory = args.directory +else: + directory = raw_input('Enter the directory of the files to be renamed: ') +if args.fileNameCSV: + fileNameCSV = args.fileNameCSV +else: + fileNameCSV = raw_input('Enter the CSV file of name changes (including \'.csv\'): ') +if args.makeChanges: + makeChanges = args.makeChanges +else: + makeChanges = raw_input('Enter "true" to if the script should actually rename the directories (otherwise, it will only create a log of the expected directory name changes): ') + +startTime = time.time() +print startTime f=csv.writer(open('renameLog'+datetime.now().strftime('%Y-%m-%d %H.%M.%S')+'.csv','wb')) f.writerow(['oldLocation']+['newLocation']) -for root, dirs, files in os.walk(filePath, topdown=True): - for dir in dirs: - with open('FolderNames.csv') as csvfile: +for root, dirs, files in os.walk(directory, topdown=False): + for dir in dirs : + print dir + with open(fileNameCSV) as csvfile: reader = csv.DictReader(csvfile) for row in reader: oldFolder = row['oldFolder'] @@ -17,4 +39,12 @@ oldPath = os.path.join(root,dir) newPath = os.path.join(root,newFolder) f.writerow([oldPath]+[newPath]) - os.rename(oldPath,newPath) + if makeChanges == 'true': + os.rename(oldPath,newPath) + else: + print 'log of expected directory name changes created only, no files renamed' + +elapsedTime = time.time() - startTime +m, s = divmod(elapsedTime, 60) +h, m = divmod(m, 60) +print 'Total script run time: ', '%d:%02d:%02d' % (h, m, s)