Skip to content

Instantly share code, notes, and snippets.

@brianteachman
Created June 27, 2014 20:18
Show Gist options
  • Save brianteachman/b0b21555e2cd4228300f to your computer and use it in GitHub Desktop.
Save brianteachman/b0b21555e2cd4228300f to your computer and use it in GitHub Desktop.
Python function that updates first two characters (should be string integers) of each filename in a directory, starting at a given number.
import os
def update_increment(start_number, directory=None, direction='increment'):
if directory is None:
directory = os.path.abspath('.')
for file_name in os.listdir(directory):
# The two characters of the filename are numbers
file_number = int(file_name[0:2])
if file_number >= start_number:
if direction is 'decrement':
file_number -= 1
else:
file_number += 1
# Pad single-digit numbers with a 0 using string formatting
new_file_name = '%s\%02d%s' % (directory, file_number, file_name[2:])
old_file_name = '%s\%s' % (directory, file_name)
#print(old_file_name + "\n changed to: \n" + new_file_name + "\n")
os.rename(old_file_name, new_file_name)
#PATH = os.path.abspath('data')
# Increment all files starting at number 10
#update_increment(10, PATH)
# Decrement all files starting at number 10
#update_increment(10, PATH, 'decrement')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment