Skip to content

Instantly share code, notes, and snippets.

@twitu
Created March 18, 2020 18:24
Show Gist options
  • Save twitu/8923d54278e3e4a75522cc27088f6256 to your computer and use it in GitHub Desktop.
Save twitu/8923d54278e3e4a75522cc27088f6256 to your computer and use it in GitHub Desktop.
Pad numeral part in file name to correctly order files
#!/usr/bin/python3
import os
import re
import sys
import argparse
def match_files(regex):
return [name for name in os.listdir() if regex.match(name)]
# regex should group on the numeral part of file name
def pad_length(regex, files):
max_num = max([int(regex.search(filename).group(1)) for filename in files])
return len(str(max_num))
def new_file_names(pad, files):
matches = [(regex.search(filename).group(1), filename) for filename in files]
return [name.replace(m, m.zfill(pad)) for (m, name) in matches]
def rename_files(names, new_names):
for (name, new_name) in zip(names, new_names):
os.rename(name, new_name)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Pad numbers in file name')
parser.add_argument("regex", help='regex pattern for file which groups numerical pattern. for e.g. playlist_(\d*)_.*_album.mp3', type=str, action='store')
parser.add_argument('--debug', '-d', help='perform a dry run without actually changing file names', action='store_true')
args = parser.parse_args()
regex = re.compile(args.regex)
debug = args.debug
names = match_files(regex)
pad = pad_length(regex, names)
new_names = new_file_names(pad, names)
if debug:
print("{} files found".format(len(names)))
print('\n'.join(names))
print()
print("New names")
print('\n'.join(new_names))
else:
rename_files(names, new_names)
@twitu
Copy link
Author

twitu commented Mar 18, 2020

Usage

  1. Save the file as 'pad_file_name.py'
  2. chmod +x pad_file_name.py
  3. mv pad_file_name.py /usr/bin/
  4. cd directory/where/files/names/are/not/padded
  5. run script with a regex for the files

Example

pad_file_name.py --debug "playlist_(\d+)_.*_album.mp3"
pad_file_name.py "playlist_(\d+)_.*_album.mp3"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment