首页 > 解决方案 > 使用 Python 获取目录中文件列表的修改日期的最快方法是什么?

问题描述

我在一个包含大量 csv 文件(500+)的目录中有一个文件夹。我只需要在某个日期之后具有修改日期的 csv 文件。最终,我会将这些文件 pd.concat 放入一个 pandas 数据框中。

获得相关文件概览的最快方法是什么?

我目前的解决方案如下所示:

## get list of files
list_of_files = glob.glob(Path + '*.csv')

## transform to datataframe
df_files = pd.DataFrame(list_of_files, columns = ['files'])

## Calculate modification time (SLOW)
df_files['Modification_Time'] = df_files['files'].apply(lambda x: datetime.date.fromtimestamp(os.path.getmtime(x)))

## Eventually filter based on Modification date and pd.concat relevant files (code not relevant for the question)

我的解决方案相当慢,我想知道是否有更快的解决方案?

标签: pythonpandastime

解决方案


尝试在初始化数据框之前评估修改时间 -

import glob

result=  []
for file in glob.glob(Path + '*.csv'):
    temp = {
        'files': file,
        'Modification_Time': datetime.date.fromtimestamp(
            os.path.getmtime(file)
        ),
    }
    result.append(temp)
    
df_files = pd.DataFrame(result)

推荐阅读