Created
April 23, 2014 04:28
-
-
Save frankcleary/11202739 to your computer and use it in GitHub Desktop.
Rename figure files (figure 3.jpg -> figure 4.jpg)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Rename a list of figures, making space for a new figure | |
Ex: Figure 1, Figure 2, Figure 3 -> Figure 1, Figure 3, Figure 4 | |
""" | |
import sys | |
import os | |
import re | |
def get_file_list(): | |
"""Return a list of files in the current directory""" | |
file_list = os.listdir(os.getcwd()) | |
return file_list | |
def number_from_name(fname): | |
"""Return figure number by matching regex to fname""" | |
match = re.match(r'figure (\d+)', fname, flags=re.IGNORECASE) | |
if match is not None: | |
fignum = int(match.group(1)) | |
return fignum | |
else: | |
return None | |
def rename(fname, new_figure_number, diff=1): | |
"""Rename fname by incrementing its number by diff, only if its number is | |
greater than new_figure_number. | |
""" | |
fignum = number_from_name(fname) | |
if fignum is not None and fignum >= new_figure_number: | |
new_name_string = 'Figure {}'.format(fignum + diff) | |
new_fname = re.sub('Figure \d+', new_name_string, | |
fname, flags=re.IGNORECASE) | |
os.rename(fname, new_fname) | |
if __name__ == "__main__": | |
if len(sys.argv) != 2: | |
print "usage: figure_rename.py n" | |
print "where n is the number of the new figure" | |
sys.exit() | |
file_list = get_file_list() | |
file_list.sort(key=number_from_name,) | |
try: | |
new_figure_number = int(sys.argv[1]) | |
except ValueError: | |
print "n must be an integer" | |
sys.exit() | |
for fname in reversed(file_list): | |
rename(fname, new_figure_number) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment