题目来源:http://www.cnblogs.com/vamei/archive/2012/08/31/2661870.html
推荐博客园的一个学习Python的快速教程
http://www.cnblogs.com/vamei/archive/2012/09/13/2682778.html
练习题:
有一个文件,文件名为output_1981.10.21.txt 。下面使用Python: 读取文件名中的日期时间信息,并找出这一天是周几。将文件改名为output_YYYY-MM-DD-W.txt (YYYY:四位的年,MM:两位的月份,DD:两位的日,W:一位的周几,并假设周一为一周第一天)
import re
import time
import datetime
filename = "output_1981.10.21.txt"
m = re.search("output_(\d{4}.\d{2}.\d{2})", filename)
searchResult = m.group(1)
print ("matcht result: %s" % searchResult)
dates = searchResult.split('.')
for date in dates:
print date
year = dates[0]
month = dates[1]
day = dates[2]
xingqi = datetime.datetime(int(year), int(month), int(day)).strftime("%w")
# replace to new filename
theReplacePart = '%s-%s-%s-%s' % (year,month,day,xingqi)
print 'the new filename is: %s' % theReplacePart
newfileName = re.sub("\d{4}.\d{2}.\d{2}", theReplacePart, filename)
print newfileName
最近在学习Python,这是我的解答,欢迎大家贴上自己的答案