首页 > 解决方案 > 使用 re.compile 提取最近日期的文件

问题描述

我对 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)

标签: pythonregex

解决方案


这应该会有所帮助。使用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)

推荐阅读