从this
开始一个新主题我有一个包含这种格式文件的目录:
Report_Test-01-16-2014.09_42-en.zip
Another Report_Test-01-16-2014.09_42-en.zip
Report_Holiday-01-16-2014.09_42-en.zip
Report_Weekday-01-16-2014.09_42-en.zip
Report_Special-01-16-2014.09_42-en.zip
Report_Test-12-16-2013.10_52-en.zip
Another Report_Test-12-16-2013.10_52-en.zip
Report_Holiday-12-16-2013.10_52-en.zip
Report_Weekday-12-16-2013.10_52-en.zip
Report_Special-12-16-2013.10_52-en.zip
我无法控制文件命名,文件名模式保持一致。 我在之前的thread
中尝试了所有内容我需要能够根据文件名中的日期返回最后一个文件和最后两个文件。 不幸的是,日期的%m-%d-%Y格式让我失望。我最终得到了2013年的文件,因为2013年12月16日的12个文件在01-16-2014中高于01。
非常感谢任何建议。 感谢
答案 0 :(得分:2)
date
对象。filenames = [
'Report_Test-01-16-2014.09_42-en.zip',
'Another Report_Test-01-16-2014.09_42-en.zip',
'Report_Holiday-01-16-2014.09_42-en.zip',
'Report_Weekday-01-16-2014.09_42-en.zip',
'Report_Special-01-16-2014.09_42-en.zip',
'Report_Test-12-16-2013.10_52-en.zip',
'Another Report_Test-12-16-2013.10_52-en.zip',
'Report_Holiday-12-16-2013.10_52-en.zip',
'Report_Weekday-12-16-2013.10_52-en.zip',
'Report_Special-12-16-2013.10_52-en.zip',
] # Used in place of `os.listdir(....)`
import re
import datetime
date_pattern = re.compile(r'\b(\d{2})-(\d{2})-(\d{4})\b')
def get_date(filename):
matched = date_pattern.search(filename)
if not matched:
return None
m, d, y = map(int, matched.groups())
return datetime.date(y, m, d)
dates = (get_date(fn) for fn in filenames)
dates = (d for d in dates if d is not None)
last_date = max(dates)
last_date = last_date.strftime('%m-%d-%Y')
filenames = [fn for fn in filenames if last_date in fn]
for fn in filenames:
print(fn)
输出:
Report_Test-01-16-2014.09_42-en.zip
Another Report_Test-01-16-2014.09_42-en.zip
Report_Holiday-01-16-2014.09_42-en.zip
Report_Weekday-01-16-2014.09_42-en.zip
Report_Special-01-16-2014.09_42-en.zip
答案 1 :(得分:0)
使用.split("-")
函数。
喜欢
x="Report_Test-01-16-2014.09_42-en.zip"
y=x.split("-") #['Report_Test', '01', '16', '2014.09_42', 'en.zip']
然后进行一些排序并获得最新的
答案 2 :(得分:0)
您可以使用自己的比较功能根据您的逻辑进行比较
filenames = ["Report_Test-01-16-2014.09_42-en.zip",
"Report_Special-12-16-2013.10_52-en.zip"]
def compare_dates(fn1,fn2):
# parse the date information
day1,month1,year1 = fn1.split(".")[0].split("-")[-3:]
day2,month2,year2 = fn2.split(".")[0].split("-")[-3:]
ret = cmp(year1,year2) # first compare the years
if ret != 0:
return ret
ret = cmp(month1,month2) # if years equal, compare months
if ret != 0:
return ret
return cmp(day1,day2) # if months equal, compare days
filenames.sort(cmp=compare_dates)
现在2013年是2014年之前:
>>> filenames
['Report_Special-12-16-2013.10_52-en.zip', 'Report_Test-01-16-2014.09_42-en.zip