Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way, than this, to rename files using Python

Tags:

python

file-io

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 ?

like image 560
Ashutosh Jindal Avatar asked Nov 21 '25 17:11

Ashutosh Jindal


2 Answers

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.

like image 169
Jon-Eric Avatar answered Nov 23 '25 05:11

Jon-Eric


How about this:

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

newfilename = '%s_%s-%s-%s' % (name, day, month, timestamp)
like image 44
Wolph Avatar answered Nov 23 '25 06:11

Wolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!