Skip to content

Instantly share code, notes, and snippets.

@Akczht
Created December 13, 2024 11:53
Show Gist options
  • Save Akczht/5d3020ad5e134049e7dbb58fa5b8dcf9 to your computer and use it in GitHub Desktop.
Save Akczht/5d3020ad5e134049e7dbb58fa5b8dcf9 to your computer and use it in GitHub Desktop.
a script to add leading zeroes in a directory recursively according to the folder structures inside
import os
def rename_files_with_leading_zeroes(folder_path=os.getcwd()):
for root, _, files in os.walk(folder_path):
total_files = len(files)
# Determine the number of digits needed
digits = len(str(total_files))
# Sort files for consistent renaming order
files.sort()
for filename in files:
# Get the file name and extension
name, file_extension = os.path.splitext(filename)
# Create the new name with leading zeroes
new_name = f"{name.zfill(digits)}{file_extension}"
# Get the full paths
old_path = os.path.join(root, filename)
new_path = os.path.join(root, new_name)
# Rename the file
os.rename(old_path, new_path)
print(f"Renamed '{filename}' to '{new_name}' in folder '{root}'")
# Example usage
rename_files_with_leading_zeroes()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment