else/Toolbox/fileprefix.py

63 lines
1.7 KiB
Python
Raw Normal View History

2015-09-08 01:07:52 +00:00
'''
When you run this file from the commandline given a single argument, all
of the files in the current working directory will be renamed in the format
{argument}_{count} where argument is your cmd input and count is a zero-padded
integer that counts each file in the folder.
'''
import os
import random
import string
import re
import sys
2017-03-30 22:56:12 +00:00
assert len(sys.argv) in range(2, 4)
2015-09-09 07:32:14 +00:00
ctime = '-c' in sys.argv
2017-03-30 22:56:12 +00:00
dry = '--dry' in sys.argv
2015-09-09 07:32:14 +00:00
IGNORE_EXTENSIONS = ['.py', '.lnk']
2015-09-08 01:07:52 +00:00
prefix = sys.argv[1]
2015-10-03 23:29:52 +00:00
if prefix != '':
prefix += '_'
2015-09-08 01:07:52 +00:00
files = [os.path.abspath(x) for x in os.listdir()]
files = [item for item in files if os.path.isfile(item)]
if __file__ in files:
files.remove(__file__)
# trust me on this.
zeropadding = len(str(len(files)))
zeropadding = max(2, zeropadding)
zeropadding = str(zeropadding)
2015-10-03 23:29:52 +00:00
format = '%s%0{pad}d%s'.format(pad=zeropadding)
2015-09-08 01:07:52 +00:00
def natural_sort(l):
'''
http://stackoverflow.com/a/11150413
'''
convert = lambda text: int(text) if text.isdigit() else text.lower()
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(l, key=alphanum_key)
2015-09-09 07:32:14 +00:00
if ctime:
print('Sorting by time')
files.sort(key=os.path.getctime)
else:
print('Sorting by name')
files = natural_sort(files)
2015-09-08 01:07:52 +00:00
for (fileindex, filename) in enumerate(files):
if '.' in filename:
extension = '.' + filename.split('.')[-1]
2015-09-09 07:32:14 +00:00
if extension in IGNORE_EXTENSIONS:
continue
2015-09-08 01:07:52 +00:00
else:
extension = ''
newname = format % (prefix, fileindex, extension)
2016-01-17 01:43:17 +00:00
if os.path.basename(filename) != newname:
print(''.join([c for c in (filename + ' -> ' + newname) if c in string.printable]))
2017-03-30 22:56:12 +00:00
if not dry:
os.rename(filename, newname)
if dry:
print('Dry. No files renamed.')