Skip to content

Instantly share code, notes, and snippets.

@reinecke
Last active February 13, 2019 06:34
Show Gist options
  • Save reinecke/6aea76678d876aa8d3fc8068e6ba8284 to your computer and use it in GitHub Desktop.
Save reinecke/6aea76678d876aa8d3fc8068e6ba8284 to your computer and use it in GitHub Desktop.
Example script that renames the exr files in a folder with the folder name, assuming the files have a name like base.00001.exr.
"""
File renamer script.
Built to be packaged into a progress bar app and run using Platypus: https://sveinbjorn.org/platypus
"""
import math
import os
import sys
import traceback
# only files of this type will be renamed
RENAME_TYPES = [".exr"]
def report_progress(complete, total):
"""
Prints progess in the format platypus will populate it's progress bar with.
"""
# Calculate percentage
percentage = (float(complete) / total) * 100
percentage_string = math.floor(percentage)
print("PROGRESS:{}".format(percentage_string))
def show_alert(title, text):
"""
Shows an alert window (using platypus' format) with the provided title and
text.
"""
print("ALERT:{}|{}".format(title, text))
class DropletError(Exception):
""" Raise to display an error window with the text of this exception """
def rename_contents(folder_path):
# Get the name of the folder off the end of the full path
folder_name = os.path.basename(folder_path)
# Step through the files in the folder and rename them
filenames = os.listdir(folder_path)
total_files = len(filenames)
renamed_file_count = 0
for i, fname in enumerate(filenames):
report_progress(i, total_files)
# Get the file extension (.exr for example)
file_base, extension = os.path.splitext(fname)
# Compare the lowercase version of the extension to make sure it's
# in the allow list
if extension.lower() not in RENAME_TYPES:
# if it's not, skip it
continue
# Files are named like C306C001_181214IM.0001.exr, we dropped the ext
# Split on . and make sure it matches the expected format
name_components = file_base.split(".")
if len(name_components) != 2:
print(
"unexpected number of '.' in file name: {}".format(fname)
)
continue
# make sure the last component is a number
number_component = name_components[1]
try:
int(number_component)
except ValueError:
print(
"Expected number in last component of file name: {}".format(
fname
)
)
continue
# Build the new name and re-construct the full file path
new_name = "{folder_name}.{number_component}{extension}".format(
folder_name=folder_name,
number_component=number_component,
extension=extension,
)
new_path = os.path.join(folder_path, new_name)
old_path = os.path.join(folder_path, fname)
# rename the file!
os.rename(old_path, new_path)
# Keep track of the number of files we renamed
renamed_file_count += 1
# Report the progress with plus one to make sure it'll read 100 in the
# end
report_progress((i + 1), total_files)
# Tell the caller how many of the files were renamed
return (renamed_file_count, total_files)
def main():
# Reset any output in platypus and make sure the output log is displayed
print("REFRESH")
print("DETAILS:SHOW")
# Get the arguments passed to the script (except the first one, which is
# the name of the script itself
args = sys.argv[1:]
num_args = len(args)
for i, argument in enumerate(args):
print("Processing {} ({} of {})".format(argument, (i + 1), num_args))
# Skip anything that isn't a folder
if not os.path.isdir(argument):
continue
renamed_count, total_count = rename_contents(argument)
print(
"folder {} complete, {} of {} files renamed".format(
argument, renamed_count, total_count
)
)
if __name__ == "__main__":
try:
main()
except DropletError as e:
# If this exception type was raised, it was meant to be format as an
# error
show_alert("Error", str(e))
except Exception as e:
# Display any uncaught exceptions so we can address
show_alert("Unexpected Error", traceback.format_exc())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment