使用re.compile提取最新日期的文件

时间:2018-07-10 03:03:50

标签: python regex

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

1 个答案:

答案 0 :(得分:0)

这应该有所帮助。使用 def clean_bulk_add(self): assig1 = self.cleaned_data['name'] course1 = self.this_course user1 = course1.owner tot1 = 30 + len(str(user1)) + len(str(course1.title)) + len(str(assig1)) + len(str(self.cleaned_data['bulk_add'])) if tot1 > 7 : raise forms.ValidationError("Assignment or Course name is too long: "+str(tot1)) return self.cleaned_data['bulk_add']

例如:

datetime.datetime.strptime