Better way, than this, to rename files using Python
I am python开发者_StackOverflow社区 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 ?
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.
How about this:
name, timestamp = oldfilename.split('_', 1)
day, month, timestamp = timestamp.split('-', 2)
newfilename = '%s_%s-%s-%s' % (name, day, month, timestamp)
精彩评论