仅一次打开并读取最新的json文件

问题描述 投票:3回答:1

SO成员...我如何只能一次读取目录中的最新json文件(如果没有新文件打印出什么内容)。到目前为止,我只能读取最新的文件...下面打开的示例脚本(每45分钟运行一次)并读取目录中的最新json文件。在这种情况下,最新文件为file3.json(每30分钟创建一次json文件)。因此,如果由于某种原因未创建file4(例如,服务器无法创建新的json文件)。如果脚本再次运行..它将仍然读取相同的最后一个文件3。

目录中的文件

file1.json
file2.json
file3.json

下面的脚本能够打开和读取在目录中创建的最新json文件。

import glob
import os
import os.path
import datetime, time

listFiles = glob.iglob('logFile/*.json') 
latestFile = max(listFiles, key=os.path.getctime)
with open(latestFile, 'r') as f:
   mydata = json.load(f)
   print(mydata)

为了确保脚本仅读取最新文件并仅读取一次最新文件,请注意以下事项:-

listFiles = glob.iglob('logFile/*.json') 
latestFile = max(listFiles, key=os.path.getctime)
if latestFile newer than previous open/read file: # Not sure to compare the latest file with the previous file.
    with open(latestFile, 'r') as f:
       mydata = json.load(f)
       print(mydata)
else:
    print("no new file created")

谢谢您的帮助。示例解决方案可以很好地共享。


我不知道解决方案...似乎很简单,但是几天尝试n错误而没有运气。

(1)Make sure read latest file in directory 
(2)Make sure read file/s that may miss to read (due to script fail to run)
(3)Only read once all the files and if no new file give warning.

谢谢。

python json file glob
1个回答
3
投票

下面是答案,而是一种方法,我想提出:

enter image description here

想法如下:每个写入目录的日志文件都可以在其中包含一个称为"creation_time": timestamp的键值(存储在服务器中的fileX.json)。现在,您的脚本在45min运行,以获取转储到目录的文件。通常情况下,您必须能够读取文件,最后,退出脚本时,可以将最后读取的文件名和从fileX.json中获取的creation_time存储到logger.json中。logger.json的示例如下:

{
"creation_time": "03520201330",
"file_name": "file3.json"
}  

[每当服务器发生故障或发生任何延迟时,都可能会重写fileX.json或在目录中创建了new fileX's.json。在这些情况下,您将首先打开logger.json并获取时间戳和最后一个文件名,如上面的示例所示。通过使用最后一个文件名,您可以将记录器中存在的旧时间戳与fileX.json中的新时间戳进行比较。如果它们基本匹配,则没有任何变化,您只能预读文件并重写记录器。如果不是这种情况,您将再次重新读取最后一个fileX.json,然后继续读取其他前面的文件。

© www.soinside.com 2019 - 2024. All rights reserved.