【问题标题】:Using re.compile to extract file with most recent date使用 re.compile 提取最近日期的文件
【发布时间】:2018-07-10 14:05:28
【问题描述】:

我是 Python 的新手,我正在尝试使用 Python 3.6 从文件夹中提取最新的文件。

我正在努力使用 re.compile 匹配文件名。如何从文件列表中识别最新文件以将其导入 python?我还想从文件名中提取日期。

文件名的示例是“VAL-FTS_Opals_20180706.xls”

我的代码如下:

import os

# Import pandas
import pandas as pd
#Import re & datetime for date identification & handling
import re
import datetime


# Retrieve current working directory (`cwd`)
cwd = os.getcwd()
cwd
# Change directory 
os.chdir('E:\Python\Portfolio Data')

# List all files and directories in current directory
filelist = os.listdir('.')


#Extract date string from the filenames
date_pattern = re.compile(r'\d{8}')

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 filelist)
dates = (d for d in dates if d is not None)
#Find the last date
last_date = max(dates)

【问题讨论】:

  • 我不知道为什么你有 **date_pattern,它应该只是 date_pattern 并且你在那一行还有一个未闭合的字符串。对于最近的文件,试试max(fillelist, key=get_date)
  • 如果你有那些格式完美(用于日期比较)的文件名,你根本不需要从 RegEx 开始。您可以使用 filename[-12:-4] 来获取日期字符串并对其进行排序。
  • 如果所有文件名的格式都是VAL-FTS_Opals_YYYYMMDD.xls,那么文件排序(降序)列表中的第一个元素不是最近的文件吗?

标签: python regex


【解决方案1】:

这应该会有所帮助。使用datetime.datetime.strptime

例如:

date_pattern = re.compile(r'(?P<date>\d{8})')

def get_date(filename):
    matched = date_pattern.search(filename)
    if not matched:
        return None
    return datetime.datetime.strptime(matched.groups('date')[0], "%Y%m%d")

dates = (get_date(fn) for fn in filelists)
dates = (d for d in dates if d is not None)

last_date = max(dates)

【讨论】:

  • 太棒了。谢谢拉克什。太好了。
猜你喜欢
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-04
  • 1970-01-01
相关资源
最近更新 更多