Created
November 13, 2019 17:16
-
-
Save lucadealfaro/33d67e0a94277a80fa7a942a8512befc to your computer and use it in GitHub Desktop.
Renames filenames according to the date they have been taken. A file will receive a name such as 2019-07-23_13-43-27_R0000666.jpg, where R0000666.jpg is the filename before renaming. Collisions are avoided, and files which already begin by "20" are not renamed.
This file contains hidden or 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
#!/usr/bin/python | |
import argparse | |
import os | |
import shutil | |
import subprocess | |
exifcmd = "/usr/local/bin/exiftool" | |
def main(args): | |
for full_path in args.filenames: | |
path, fn = os.path.split(full_path) | |
if fn.startswith('20'): | |
# We don't rename files that already begin with the year. | |
print("Skipping %s" % full_path) | |
continue | |
process = subprocess.Popen([exifcmd, full_path], stdout=subprocess.PIPE) | |
out, _ = process.communicate() | |
exiflines = out.split('\n') | |
for l in exiflines: | |
if l.startswith("Create Date"): | |
w = l.split() | |
new_fn = w [-2] + "_" + w [-1] + "_" + fn | |
new_fn = new_fn.replace(":", "-") | |
new_fn = new_fn.replace(" ", "_") | |
new_path = os.path.join(path, new_fn) | |
# Checks that there is not a file already. | |
while os.path.exists(new_path): | |
pieces = new_path.split(".") | |
pieces[-2] += '_b' | |
new_path = ".".join(pieces) | |
shutil.move(full_path, new_path) | |
print("%s --> %s" % (full_path, new_path)) | |
# Done for this file | |
break | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument('filenames', type=str, default=None, | |
nargs="*", help="Files to rename") | |
args = parser.parse_args() | |
main(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment