python - 使用 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)
解决方案
这应该会有所帮助。使用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)
推荐阅读
- android - Kotin lateinit Var 未初始化 - Android Studio
- python-3.x - NOOB 问题:VS 代码无法正常工作
- javascript - AJAX 调用转到文件位置而不是实际 URL
- c# - 围绕鼠标点缩放自绘窗口
- python - Marshmallow_MongoEngine:ModuleNotFoundError:没有名为“marshmallow.compat”的模块
- arrays - 雄辩的 where 子句不采用关联数组
- android - (React-Native 0.62.0)无法找到项目的匹配变体:react-native-community_async-storage(其他库也一样)
- javascript - LitElement - 如果值为 false,则不要添加属性
- r - 在 R 中对多个条件使用 rle() 函数
- java - Java Spark Map 错误:错误执行程序:阶段 0.0 spark scala 中的任务 0.0 异常?