Python快速读取文件系统

2024-09-30 14:31:19 发布

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

我有一个python脚本,每次执行时都会编写四个JSON文件(几个键、值对)。该脚本每天执行大约10万次,每天生成40万个文件。每次执行都会在一个带计数器的带日期的目录中生成四个JSON文件,例如:

  • /30/04/2021/run1/

  • /30/04/2021/run2/

  • /30/04/2021/run100k/

  • /01/05/2021/run1/

  • /02/05/2021/run2/

  • /31/05/2021/run100k/

我正在为此公开readapi(get_runs),人们可以在给定的日期范围内请求数据

def get_runs(from_date, to_date):
   files = []

   # construct file paths for the given date range (from_date, to_date)
   # append file paths to files 

   # call read_files
   return _read_files(files)

def _read_files(files):
   import json
   data = []
   for file in files:
      with open(file) as f:
          data.append(json.load(f))
   return data 

如果您注意到,在get_runs API调用中,我正在循环中逐个读取已过期目录(在给定范围内)中的文件,但这需要很多时间才能完成。对如何优化这一点有什么建议吗?我希望这是超快速的-注意,我不能将这些JSON对象存储在数据库中


Tags: 文件to目录脚本jsonreaddataget