Search code examples
pythonfiledaterenamecreation

Python File Creation Date & Rename - Request for Critique


Scenario: When I photograph an object, I take multiple images, from several angles. Multiplied by the number of objects I "shoot", I can generate a large number of images. Problem: Camera generates images identified as, 'DSCN100001', 'DSCN100002", etc. Cryptic.

I put together a script that will prompt for directory specification (Windows), as well as a "Prefix". The script reads the file's creation date and time, and rename the file accordingly. The prefix will be added to the front of the file name. So, 'DSCN100002.jpg' can become "FatMonkey 20110721 17:51:02". The time detail is important to me for chronology.

The script follows. Please tell me whether it is Pythonic, whether or not it is poorly written and, of course, whether there is a cleaner - more efficient way of doing this. Thank you.

   import os
   import datetime
   target = raw_input('Enter full directory path: ')
   prefix = raw_input('Enter prefix: ')
   os.chdir(target)
   allfiles = os.listdir(target)
   for filename in allfiles:
        t = os.path.getmtime(filename)
        v = datetime.datetime.fromtimestamp(t)
        x = v.strftime('%Y%m%d-%H%M%S')
        os.rename(filename, prefix + x +".jpg")

Solution

  • The way you're doing it looks Pythonic. A few alternatives (not necessarily suggestions):

    You could skip os.chdir(target) and do os.path.join(target, filename) in the loop.

    You could do strftime('{0}-%Y-%m-%d-%H:%M:%S.jpg'.format(prefix)) to avoid string concatenation. This is the only one I'd reccomend.

    You could reuse a variable name like temp_date instead of t, v, and x. This would be OK.

    You could skip storing temporary variables and just do:

    for filename in os.listdir(target):
        os.rename(filename, datetime.fromtimestamp(
                             os.path.getmtime(filename)).strftime(
                              '{0}-%Y-%m-%d-%H:%M:%S.jpeg'.format(prefix)))
    

    You could generalize your function to work for recursive directories by using os.walk().

    You could detect the file extension of files so it would be correct not just for .jpegs.

    You could make sure you only renamed files of the form DSCN1#####.jpeg