繁体   English   中英

获取基于文件名python的最新文件

[英]get latest file based on filename python

开始从一个新的线程

我有一个包含这种格式文件的目录:

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

我无法控制文件命名,文件名模式保持一致。 我在前一个帖子中尝试过所有内容

我需要能够根据文件名中的日期返回最后一个文件和最后两个文件。 不幸的是,日期的%m-%d-%Y格式让我失望。 我最终得到了2013年的文件,因为2013年12月16日的12个比2014年1月16日的01高。

任何建议将非常感谢。 谢谢

  • 从文件名中提取日期字符串。
  • 将其转换为date对象。
  • 找到最后的日期。 (1)
  • 使用上次日期过滤文件名。

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

使用.split("-")函数。 喜欢

x="Report_Test-01-16-2014.09_42-en.zip"
y=x.split("-") #['Report_Test', '01', '16', '2014.09_42', 'en.zip']

然后做一些并得到最新的

您可以使用自己的比较功能根据您的逻辑进行比较

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM