【问题标题】:What is the fastest way to get modification date of a list of files in a directory using Python?使用 Python 获取目录中文件列表的修改日期的最快方法是什么?
【发布时间】:2021-07-23 22:29:30
【问题描述】:

我在包含大量 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)

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

【问题讨论】:

    标签: python pandas time


    【解决方案1】:

    其他答案都没有解决您的根本问题 - 确保避免加载数据帧是明智的,但它不会加快您的 getmtime 调用。

    实际上,当您可以进行一次调用时,您实际上是在对文件表进行多次调用。不要使用glob,而是使用os.scandir(python 3.5+),这将允许您列出目录中的所有文件并在一次调用中查看修改时间。在 Windows 上,这几乎快 10 倍,因为 Windows 文件系统会自动响应修改后的时间 - glob 只是没有将它暴露给您。在 *nix 上,速度提升较小(2 倍? - 请参阅 https://www.python.org/dev/peps/pep-0471/

    所以你想要类似的东西

    import os
    
    scan_of_files = os.scandir(Path)
    name_with_times = {f.name : datetime.fromtimestamp(f.stat().st_mtime) 
                               for f in scan_of_files if f.name[-4:] == ".csv"}
    

    【讨论】:

      【解决方案2】:

      在加载之前确定您想要的文件:

      from datetime import datetime
      
      # Find files that were modified after 7PM on 2021-04-30
      mtime = datetime(2021, 4, 30, 19, 0, 0).timestamp()
      
      list_of_files = [
          file for file in glob.glob(path + '*.csv')
              if os.path.getmtime(file) > mtime
      ]
      

      【讨论】:

        【解决方案3】:

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

        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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-03-29
          • 1970-01-01
          • 2021-12-07
          • 1970-01-01
          • 2016-12-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多