在文件夹中查找每个日历月的最新文件

2024-04-25 07:27:12 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码工作,因为我需要它,但我觉得必须有一个更好的方法。我有一个文件夹,里面有每日(ish)文件。它们都有相同的前缀和发送日期作为文件名。但在某些日子里,根本没有发送任何文件。我的任务是读取每个月的最后一个文件(大部分时间是最后一天,但是四月的最后一个文件是28号,七月是29号,等等)。你知道吗

这是使用pathlib模块,我想继续使用它。你知道吗

files = sorted(ROOT.glob('**/*.csv*'))
file_dates = [Path(file.stem).stem.replace('prefix_', '').split('_') for file in files] #replace everything but a list of the date elements
dates = [pd.to_datetime(date[0] + '-' + date[1] + '-' + date[2]) for date in file_dates] #construct the proper date format
x = pd.DataFrame(dates)
x['month'] = x[0].dt.strftime('%Y-%m') + '-01'
max_value = x.groupby(['month'])[0].max().reset_index()
max_value[0] = max_value[0].dt.strftime('%Y_%m_%d')
monthly_files = [str(ROOT / 'prefix_') + date + '.csv.xz' for date in max_value[0].values]

df = pd.concat([pd.read_csv(file, usecols=columns, sep='\t', compression='xz', dtype=object) for file in monthly_files])

我相信这是一个例子,因为我有一个锤子(熊猫),一切看起来像钉子(我把一切变成一个数据帧)。我也试着在几年不使用理解列表后习惯它们。你知道吗


Tags: 文件csvinfordateprefixvalueroot
3条回答

所以文件名是prefix_<date>,日期的格式是%Y-%m-%d。你知道吗

import os
from datetime import datetime as dt
from collections import defaultdict
from pathlib import Path

group_by_month = defaultdict(list)
files = []

# Assuming the folder is the data folder path itself.
for file in Path(folder).iterdir():
    if os.path.isfile(file) and file.startswith('prefix_'):
        # Convert the string date to a datetime object
        converted_dt = dt.strptime(str(file).split('prefix_')[1], 
                                   '%Y-%m-%d')

        # Group the dates by month
        group_by_month[converted_dt.month].append(converted_dt)

# Get the max of all the dates stored.
max_dates = {month: max(group_by_month[month]) 
             for month in group_by_month.keys()}

# Get the files that match the prefix and the max dates
for file in Path(folder).iterdir():
    for date in max_date.values():
        if ('prefix_' + dt.strftime(date, '%Y-%m-%d')) in str(file):
            files.append(file)

附言:我很少和pandas合作。因此,使用本地样式来获取与一个月的最大日期匹配的文件。你知道吗

据我所知,这将是很难做到与列表理解,因为你必须比较当前的元素与下一个元素。你知道吗

然而,有更简单的解决方案,将使你没有熊猫那里。你知道吗

下面的示例只是循环一个带有文件日期的字符串列表,并将日期保留在月份更改之前。既然你的单子已经排序了,那就可以了。我假设YYYY\u MM\u DD日期格式

files = sorted(ROOT.glob('**/*.csv*'))
file_dates = [Path(file.stem).stem.replace('prefix_', '') for file in files] 

#adding a dummy date because we're comparing to the next element
file_dates.append('0000_00_00')
result = []
for i, j in enumerate(file_dates[:-1]):
    if j[6:7] != file_dates[i+1][6:7]: 
        result.append(j)

monthly_files = [str(ROOT / 'prefix_') + date + '.csv.xz' for date in result]

df = pd.concat([pd.read_csv(file, usecols=columns, sep='\t', compression='xz', dtype=object) for file in monthly_files])

可能有更好的,但我的尝试是:

files = sorted(ROOT.glob('**/*.csv*'))
file_dates = [Path(file.stem).stem.replace('prefix_', '').split('_') for file in files] #replace everything but a list of the date elements

df = pd.DataFrame(file_dates, columns=['y', 'm', 'd'], dtype='int')
monthly = [str(yy)+'-'+str(mm)+'-'+str(df.loc[(df['y'] == yy) & (df['m'] == mm), 'd'].max()) for yy in df.y.unique() for mm in df.m.unique()]

相关问题 更多 >