Skip to content

Instantly share code, notes, and snippets.

@WouterStemgee
Last active August 13, 2022 17:46
Show Gist options
  • Save WouterStemgee/71ee21b71e98a64cab53f4fcda6e16eb to your computer and use it in GitHub Desktop.
Save WouterStemgee/71ee21b71e98a64cab53f4fcda6e16eb to your computer and use it in GitHub Desktop.
Rename filenames in directory structure based on their folder index
import os
import re
# file rename example:
# sub-directory: "1. Introduction"
# files: "1. foo", "2. bar", ... => "1.1 foo", "1.2 bar", ...
path = '.'
for root, dirs, files in os.walk(path):
for file_name in files:
file_path = os.path.join(root, file_name)
print(file_path)
index_regex = re.compile(r'\/(\d+)\.')
if re.search(index_regex, file_path):
file_index = re.search(index_regex, file_path).group(1)
new_file_path = os.path.join(root, file_index + '.' + file_name)
print(new_file_path)
os.rename(file_path, new_file_path)
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment