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")
感谢您的帮助。示例解决方案很适合分享。
我想不出解决方案...看起来很简单,但几天都没有任何运气尝试错误。
(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.
谢谢。
经过 SO 讨论和建议后,我几乎没有办法解决或至少满足一些要求。我只是移动已经处理过的文件。如果没有创建文件,脚本将不运行,如果脚本失败,一旦正常化,它将运行并读取所有可用的相关文件。我认为它现在很好。谢谢你...
最佳答案
下面是答案而不是一种方法,我想建议:
思路如下:
写入目录的每个日志文件都可以有一个名为 "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
并继续读取其他前面的文件。
关于python - 只打开和读取最新的 json 文件一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61553592/