cmd/fileprefix.py

110 lines
3.3 KiB
Python
Raw Normal View History

2019-06-12 05:41:31 +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 argparse
import os
import re
import sys
from voussoirkit import getpermission
2019-06-12 05:41:31 +00:00
from voussoirkit import pathclass
from voussoirkit import safeprint
IGNORE_EXTENSIONS = ['py', 'lnk', 'ini']
def natural_sorter(x):
'''
2020-04-03 03:29:22 +00:00
Thank you Mark Byers
2019-06-12 05:41:31 +00:00
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 alphanum_key(x)
def fileprefix(
prefix='',
sep='_',
ctime=False,
autoyes=False,
2020-11-03 00:23:32 +00:00
one_index=False,
2019-06-12 05:41:31 +00:00
):
2020-09-22 08:56:17 +00:00
current_directory = pathclass.cwd()
2019-06-12 05:41:31 +00:00
prefix = prefix.strip()
if prefix == ':':
prefix = current_directory.basename + ' - '
elif prefix != '':
prefix += sep
filepaths = current_directory.listdir()
filepaths = [f for f in filepaths if f.is_file]
filepaths = [f for f in filepaths if f.extension not in IGNORE_EXTENSIONS]
2019-06-12 05:41:31 +00:00
try:
pyfile = pathclass.Path(__file__)
filepaths.remove(pyfile)
except ValueError:
pass
# trust me on this.
zeropadding = len(str(len(filepaths)))
zeropadding = max(2, zeropadding)
zeropadding = str(zeropadding)
format = '{{prefix}}{{index:0{pad}d}}{{extension}}'.format(pad=zeropadding)
if ctime:
print('Sorting by time')
filepaths.sort(key=lambda x: x.stat.st_ctime)
else:
print('Sorting by name')
filepaths.sort(key=lambda x: natural_sorter(x.basename))
rename_pairs = []
2020-11-03 00:23:32 +00:00
start_index = 1 if one_index else 0
for (index, filepath) in enumerate(filepaths, start_index):
extension = filepath.extension.with_dot
2019-06-12 05:41:31 +00:00
newname = format.format(prefix=prefix, index=index, extension=extension)
if filepath.basename != newname:
rename_pairs.append((filepath.absolute_path, newname))
for (oldname, newname) in rename_pairs:
message = f'{oldname} -> {newname}'
safeprint.safeprint(message)
if autoyes or getpermission.getpermission('Is this correct?'):
2019-06-12 05:41:31 +00:00
for (oldname, newname) in rename_pairs:
os.rename(oldname, newname)
def fileprefix_argparse(args):
return fileprefix(
2020-11-03 00:23:32 +00:00
autoyes=args.autoyes,
ctime=args.ctime,
one_index=args.one_index,
2019-06-12 05:41:31 +00:00
prefix=args.prefix,
sep=args.sep,
)
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('prefix', nargs='?', default='')
parser.add_argument('--sep', dest='sep', default=' ', help='the character between the prefix and remainder')
parser.add_argument('--ctime', dest='ctime', action='store_true', help='sort by ctime instead of filename')
parser.add_argument('-y', '--yes', dest='autoyes', action='store_true', help='accept results without confirming')
2020-11-03 00:23:32 +00:00
parser.add_argument('-1', dest='one_index', action='store_true')
2019-06-12 05:41:31 +00:00
parser.set_defaults(func=fileprefix_argparse)
args = parser.parse_args(argv)
return args.func(args)
2019-06-12 05:41:31 +00:00
if __name__ == '__main__':
raise SystemExit(main(sys.argv[1:]))