Skip to content

Instantly share code, notes, and snippets.

@juandesant
Last active February 3, 2025 20:17
Show Gist options
  • Select an option

  • Save juandesant/16c337e15a87f430c3ab8483ffa0506d to your computer and use it in GitHub Desktop.

Select an option

Save juandesant/16c337e15a87f430c3ab8483ffa0506d to your computer and use it in GitHub Desktop.
Rename files using os.listdir and matches, then re.sub, and os.rename
# Get files
import os
import re
# os.expanduser provides the right username based on the current user
target_files = [x for x in os.listdir(os.path.expanduser('~/Downloads'))
if x.lower().endswith('.pdf')
and x.startswith('2025_') # comment out if needed
and x.find('_recepit') != -1 # comment out if needed
]
# Change search_regexp and substitute_regexp as needed
search_regexp = r'(\d{4})_(\d{2})_(\d{2})_(\d{2})_(\d{2})_(\d{2})_(\d{3})_(.*pdf)'
substitute_regexp = r'\1-\2-\3.\4\5.\8'
# List the new names together with the old in a list of tuples
old_and_new_file_names = [
(file, re.sub(search_regexp, substitute_regexp, file))
for file in target_files
]
# Use os.rename to rename from the old to the new
for old_file_name, new_file_name in old_and_new_file_names:
os.rename(old_file_name, new_file_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment