Skip to content

Instantly share code, notes, and snippets.

@Subangkar
Created September 10, 2021 05:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Subangkar/cfd416e38564ca214a3a616cda64245d to your computer and use it in GitHub Desktop.
Save Subangkar/cfd416e38564ca214a3a616cda64245d to your computer and use it in GitHub Desktop.
Rename every file to the name of its parent folder
#!/usr/bin/env python3
# import shutil
import os
import sys
import re
from shutil import copyfile
dr = str(sys.argv[1])
ext = str(sys.argv[2])
dest = str(sys.argv[3])
DIR_SEP = '\\' if os.name == 'nt' else '/'
# print(dr, list(os.walk(dr)))
for root, dirs, files in os.walk(dr):
for file in files:
# print(file)
# print(root, f"{dr}{DIR_SEP}*{DIR_SEP}*", file, re.compile(f"{dr}{DIR_SEP}*{DIR_SEP}*").match(root))
# re.match(f"{dr}{DIR_SEP}*{DIR_SEP}*", root) and
if file.lower().endswith(ext):
spl = root.split(DIR_SEP); newname = spl[-1]; sup = (DIR_SEP).join(spl[:-1])
print('>', root, root+DIR_SEP+file, f'{dest}{DIR_SEP}{newname}.{ext}')
copyfile(f'{root}{DIR_SEP}{file}', f'{dest}{DIR_SEP}{newname}.{ext}')
# ; shutil.rmtree(root)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment