Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在文件夹中查找每个日历月的最新文件_Python_Pandas - Fatal编程技术网

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

Python 在文件夹中查找每个日历月的最新文件,python,pandas,Python,Pandas,下面的代码按照我的需要工作,但我觉得一定有更好的方法。我有一个文件夹,里面有每日(ish)文件。它们都有相同的前缀和发送日期作为文件名。但在某些日子里,根本没有发送任何文件。我的任务是阅读每个月的最后一份文件(大部分时间是最后一天,但4月的最后一份文件是28日,7月是29日,等等) 这是使用pathlib模块,我想继续使用它 files = sorted(ROOT.glob('**/*.csv*')) file_dates = [Path(file.stem).stem.replace('pre

下面的代码按照我的需要工作,但我觉得一定有更好的方法。我有一个文件夹,里面有每日(ish)文件。它们都有相同的前缀和发送日期作为文件名。但在某些日子里,根本没有发送任何文件。我的任务是阅读每个月的最后一份文件(大部分时间是最后一天,但4月的最后一份文件是28日,7月是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])

我相信这是一个例子,因为我有一把锤子(熊猫),所有东西看起来都像钉子(我把所有东西都变成了一个数据框)。经过几年的不使用,我也试着习惯于列出理解。可能有更好的方法,但下面是我的尝试:

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()]

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

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()]

因此,文件名将是
前缀
,日期的格式为
%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)

附言:我没有和熊猫一起工作过很多次。因此,使用本机样式来获取与一个月的最大日期匹配的文件。

因此文件名将是
前缀
,并且日期的格式为
%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)

附言:我没有和熊猫一起工作过很多次。因此,使用本机样式来获取与一个月的最长日期匹配的文件。

据我所知,这将很难理解列表,因为您必须将当前元素与下一个元素进行比较

然而,有一些更简单的解决方案可以让你在没有熊猫的情况下实现目标

下面的示例只是循环一个包含文件日期的字符串列表,并保留月份更改之前的日期。由于您的列表已排序,因此应该可以做到这一点。我假设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])

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

然而,有一些更简单的解决方案可以让你在没有熊猫的情况下实现目标

下面的示例只是循环一个包含文件日期的字符串列表,并保留月份更改之前的日期。由于您的列表已排序,因此应该可以做到这一点。我假设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])

酷,是的,我希望看到一个非熊猫的解决方案。我也会试试。酷,是的,我希望看到一个非熊猫的解决方案。我也会试试这个。