-
Notifications
You must be signed in to change notification settings - Fork 1
/
file2folders.py
executable file
·69 lines (58 loc) · 2.27 KB
/
file2folders.py
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
#!/usr/bin/python
import sys, os, shutil
import re
import optparse
import logging
FULLFORMAT = "%(asctime)s [%(levelname)s] [%(module)s] %(message)s"
BASICFORMAT = "%(message)s"
logger = logging.getLogger()
delimiters = " _"
multicd = re.compile(r".cd\d", re.IGNORECASE)
def file2folder(directory, simulate=False):
root = os.path.abspath(directory)
for filename in os.listdir(root):
if not os.path.isfile(os.path.join(directory, filename)):
continue
fullfile = os.path.join(root, filename)
name, extension = os.path.splitext(filename)
for delimiter in delimiters:
name = name.replace(delimiter, ".")
# renaming quirks:
name = name.replace(":.", ":")
# find multiple cd files and group them
match = multicd.search(name)
endname = name.replace(match.group(), "") if match else name
subdirname = os.path.join(root, endname)
if not os.path.isdir(subdirname):
logger.debug("mkdir %s" % subdirname)
if not simulate:
os.mkdir(subdirname)
# rename the file:
subdirname = "%s/%s%s" % (subdirname, name, extension)
logger.debug("mv %s %s" % (fullfile, subdirname))
if not simulate:
shutil.move(fullfile, subdirname)
def main():
# Setup the command line arguments.
optp = optparse.OptionParser()
# options.
optp.add_option("-v", "--verbose", dest="verbose",
help="log verbosity.", action="store_true", default=False)
optp.add_option("-s", "--simulate", dest="simulate",
help="do nothing, just simulate.", action="store_true", default=False)
opts, args = optp.parse_args()
loglevel = logging.DEBUG if opts.simulate or opts.verbose else logging.INFO
logformat = FULLFORMAT if opts.verbose else BASICFORMAT
# log to stderr in fg
logging.basicConfig(level=loglevel,
format=logformat)
if len(args) < 1:
print >> sys.stderr, "please specify a valid directory"
optp.print_help()
sys.exit(-1)
elif not os.path.isdir(args[0]):
print >> sys.stderr, "%s is not a valid directory" % args[0]
sys.exit(-1)
file2folder(args[0], opts.simulate)
if __name__ == "__main__":
main()