-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseqren.py
More file actions
79 lines (67 loc) · 2.03 KB
/
Copy pathseqren.py
File metadata and controls
79 lines (67 loc) · 2.03 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python
#
# seqren.pl
# ---------
# Copyright (c) 2017 Chandranath Gunjal. Available under the MIT License
#
# Rename given files in a sequential order as prefix_nnn
#
# Flags:
# -d dry run (don't rename the files yet)
# -s nnn starting number (defaults to 1)
# -p prefix new filename prefix
#
import getopt
import os.path
import sys
# Main
# ====
if __name__ == "__main__":
synopsis = "usage: seqren.py [-d] [-s nnn] -p prefix files..."
# print usage and exit
def usage():
print(synopsis)
sys.exit(2)
# parse command line
def parse_args(argv):
try:
opts, args = getopt.getopt(argv, "hds:p:", ["help"])
except getopt.GetoptError:
usage()
p_dryrun = False
p_seqno = 1
p_prefix = None
for opt, arg in opts:
if opt in ["-h", "--help"]:
usage()
elif opt == "-d":
p_dryrun = True
elif opt == "-s":
p_seqno = int(arg)
elif opt == "-p":
p_prefix = arg
if (p_prefix is None) or (len(args) == 0) or (p_seqno < 0):
usage()
return p_prefix, p_seqno, p_dryrun, args
# parse arguments
prefix, seqno, dryrun, file_list = parse_args(sys.argv[1:])
for x in file_list:
# valid file?
if not (os.path.exists(x) and os.path.isfile(x)):
print(f"{x:s} skipped - not a file or doesn't exist")
continue
# build new filename
path, fname = os.path.split(x)
oldname, extn = os.path.splitext(fname)
newname = f"{prefix:s}_{seqno:03d}{extn:s}"
y = os.path.join(path, newname)
# does a file with the new name exist?
if os.path.exists(y):
print(f"{x:s} skipped - a file with the new name {y:s} already exists")
continue
# rename the file
print(x, "--->", y)
if not dryrun:
os.rename(x, y)
# increment sequence number
seqno += 1