Skip to content

Instantly share code, notes, and snippets.

@simonhaenisch
Last active August 3, 2016 14:07
Show Gist options
  • Save simonhaenisch/36f3e7dd8dba51fa3d0d170363b82572 to your computer and use it in GitHub Desktop.
Save simonhaenisch/36f3e7dd8dba51fa3d0d170363b82572 to your computer and use it in GitHub Desktop.
Rename files (consecutively numbered)
#!/usr/bin/env python
import sys, os
'''
Usage: python rename-files.py [directory] [extension] [new name base]
Example: python rename-files.py . .png frame-
'''
try:
directory = sys.argv[1]
extension = sys.argv[2]
newNameBase = sys.argv[3]
except:
print("Error: Missing input argument")
print(__doc__)
exit()
# get list of files (filtered by extension)
files = [file for file in os.listdir(directory) if file.endswith(extension)]
# get length for zero padding
zeroPaddingLength = len(str(len(files)))
# rename
for i, f in enumerate(files):
newFileName = newNameBase + str(i).zfill(zeroPaddingLength) + extension
os.rename(os.path.join(directory, f), os.path.join(directory, newFileName))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment