Skip to content

Instantly share code, notes, and snippets.

@nicoknoll
Created December 11, 2016 16:08
Show Gist options
  • Save nicoknoll/85abd04b16b9b9069aa0e34dc7f75b72 to your computer and use it in GitHub Desktop.
Save nicoknoll/85abd04b16b9b9069aa0e34dc7f75b72 to your computer and use it in GitHub Desktop.
import os, sys, datetime
# Static variables
dateformat = {
"eu": "%d.%m.%Y",
"us": "%Y.%m.%d"
};
# Check that script is properly called
usageError = False
if(len(sys.argv) == 3):
file, formatFrom, formatTo = sys.argv;
else:
usageError = True
if(usageError or list(dateformat.keys()).index(formatFrom) < 0 or list(dateformat.keys()).index(formatTo) < 0):
print('Usage: python ./rename.py [eu|us] [us|eu]');
sys.exit();
# Define the rename function
def renameFiles(formatFrom, formatTo):
for filename in os.listdir("."):
filename = filename.strip()
try:
if(os.path.isfile(filename)):
filenameParts = os.path.splitext(filename);
elif(os.path.isdir(filename)):
filenameParts = (filename, '')
else:
continue;
date = datetime.datetime.strptime(filenameParts[0],formatFrom)
newFilename = date.strftime(formatTo) + filenameParts[1]
os.rename(filename, newFilename)
print("Renamed " + filename + " to " + newFilename);
except ValueError as err:
# Do nothing
print(err)
# Execte function with given formatFrom and formatTo
renameFiles(dateformat[formatFrom], dateformat[formatTo])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment