-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathrenameFiles.py
More file actions
59 lines (55 loc) · 2.27 KB
/
renameFiles.py
File metadata and controls
59 lines (55 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import os
import csv
from datetime import datetime
import time
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--directory', help='the directory of the files to \
be renamed. 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 = input('Enter the directory of the files to be renamed: ')
if args.fileNameCSV:
fileNameCSV = args.fileNameCSV
else:
fileNameCSV = input('Enter the CSV file of name changes \
(including \'.csv\'): ')
if args.makeChanges:
makeChanges = args.makeChanges
else:
makeChanges = input('Enter "true" to if the script should actually rename \
the files (otherwise, it will only create a log of the expected file name \
changes): ')
startTime = time.time()
f = csv.writer(open('renameLog' + datetime.now().strftime('%Y-%m-%d %H.%M.%S')
+ '.csv', 'w'))
f.writerow(['oldFilename'] + ['newFilename'])
for root, dirs, files in os.walk(directory, topdown=True):
for file in files:
with open(fileNameCSV) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
oldFilename = row['file']
newFilename = row['newFile']
if file == oldFilename:
print(oldFilename)
oldPath = os.path.join(root, file)
newPath = os.path.join(root, newFilename)
f.writerow([oldPath] + [newPath])
if makeChanges == 'true':
os.rename(oldPath, newPath)
else:
print('log of expected file 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))