#有一个文件,文件名为output_1981.10.21.txt 。
# 下面使用Python: 读取文件名中的日期时间信息,并找出这一天是周几。
# 将文件改名为output_YYYY-MM-DD-W.txt
# (YYYY:四位的年,MM:两位的月份,DD:两位的日,W:一位的周几,并假设周一为一周第一天)'''
解题 思路:
1、获取文件名,截取日期 ,生成日期变量参数'''
import os,re
import time,datetime
class hello:def __init__(self):print('求文件名,取出日期,算出1年中哪一天,更改文件名')def get_date(self,filename):(filepath,tempfilename) = os.path.split(filename)#将文件名和路径分割开。(shotname,extension ) = os.path.splitext(tempfilename)#分离文件名与扩展名dateStr = re.split('_',shotname)[1]date = re.split('[.]',dateStr)return date#给个时间 ,找出这一天是1年中的哪一天'''解题 思路:一年12个月的天数弄成一个list,只有2月份不确认,闰年28天,非闰年29天,得出2月份天数。求前面几个月的天数之和+当月天数,就是当当年第几天'''def which_day(self):num = 0date_list = self.get_date('D:\python\learn\output_1981.10.21.txt')year =int( date_list[0])month = int(date_list[1])day = int(date_list[2])sum = 0#计算2月份的天数if(year%4==0):num = 28elif(year%400==0):num = 28else:num =29month_list = [31, num, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]for i in range(0,month-1):sum +=month_list[i]#第几天sum +=dayreturn sum,year,month,day#获取当前系统时间 年月日 周def get_now_time(self):now = time.localtime()weekday = time.strftime('%w',now)year = datetime.datetime.now().yearmonth = datetime.datetime.now().monthday = datetime.datetime.now().dayreturn year,month,day,weekdaydef modify_filename(self,filename,newname):filepath,tempfilename = os.path.split(filename)print(filepath)print(tempfilename)os.rename(filepath+'\\'+tempfilename,filepath+'\\'+newname)print('修改成功!')fo = hello()
sum,year,month,day = fo.which_day()
print(year,'年',month,'月',day,'日是一年中的第',sum,'天')
#修改文件名称
(year1,month1,day1,weekday1) = fo.get_now_time()
print(type(year1))
newname = 'output_'+str(year1)+'-'+str(month1)+'-'+str(day1)+'-'+str(weekday1)+'.txt'
fo.modify_filename(r'D:\python\learn\output_1981.10.21.txt',newname)