views:

102

answers:

2

Hello,

I am python newbie and am still discovering its wonders.

I wrote a script which renames a number of files : from Edison_03-08-2010-05-02-00_PM.7z to Edison_08-03-2010-05-02-00_PM.7z

"03-08-2010" is changed to "08-03-2010"

The script is:

import os, os.path
location = "D:/codebase/_Backups"
files = os.listdir(location)

for oldfilename in files:
    parts = oldfilename.split("_")    
    dateparts = parts[1].split("-")

    newfilename = parts[0] + "_" + dateparts[1] + "-" + dateparts[0] + "-" + dateparts[2] + "-" + parts[2] + "_" + parts[3]

    print oldfilename + " : " + newfilename
    os.rename(os.path.join(location, oldfilename), os.path.join(location, newfilename))

What would be a better/more elegant way of doing this ?

+2  A: 

How about this:

name, timestamp = oldfilename.split('_', 1)
day, month, timestamp = timestamp.split('-', 2)

newfilename = '%s_%s-%s-%s' % (name, day, month, timestamp)
WoLpH
You are dropping the final part.
Amoss
@Amoss: and the first part. Since those aren't changed they didn't seem important to me ;)
WoLpH
This is what I was looking for. I wanted this done via some nifty string splitting which is what your code does. Thanks !
AJ
+8  A: 

datetime's strptime (parse time string) and strftime (format time string) will do most of the heavy lifting for you:

import datetime

_IN_FORMAT = 'Edison_%d-%m-%Y-%I-%M-%S_%p.7z'
_OUT_FORMAT = 'Edison_%m-%d-%Y-%I-%M-%S_%p.7z'

oldfilename = 'Edison_03-08-2010-05-02-00_PM.7z'

# Parse to datetime.
dt = datetime.datetime.strptime(oldfilename, _IN_FORMAT)

# Format to new format.
newfilename = dt.strftime(_OUT_FORMAT)

>>> print newfilename
Edison_08-03-2010-05-02-00_PM.7z

Edit: Originally I was using %H (Hour, 24-hour clock) where I should have used %I (Hour, 12-hour clock) because the OP used AM/PM. This is why my example output incorrectly contained AM instead of PM. This is all corrected now.

Jon-Eric
Nice ! I am sure this is going to come in handy. Thanks Jon-Eric !
AJ