Python File Creation Date & Rename - Request for Critique -
scenario: when photograph object, take multiple images, several angles. multiplied number of objects "shoot", can generate large number of images. problem: camera generates images identified as, 'dscn100001', 'dscn100002", etc. cryptic.
i put script prompt directory specification (windows), "prefix". script reads file's creation date , time, , rename file accordingly. prefix added front of file name. so, 'dscn100002.jpg' can become "fatmonkey 20110721 17:51:02". time detail important me chronology.
the script follows. please tell me whether pythonic, whether or not poorly written and, of course, whether there 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) 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")
the way you're doing looks pythonic. few alternatives (not suggestions):
you skip os.chdir(target)
, os.path.join(target, filename)
in loop.
you strftime('{0}-%y-%m-%d-%h:%m:%s.jpg'.format(prefix))
avoid string concatenation. 1 i'd reccomend.
you reuse variable name temp_date
instead of t
, v
, , x
. ok.
you skip storing temporary variables , 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 generalize function work recursive directories using os.walk()
.
you detect file extension of files correct not .jpeg
s.
you make sure renamed files of form dscn1#####.jpeg
Comments
Post a Comment