【发布时间】:2019-05-15 21:40:43
【问题描述】:
所以我有我的函数,它基本上检查两组数据中是否存在特定文件名。如果是这样,那么它将对文件大小进行一些计算并在终端上输出结果。由于我将一个文件名传递给 test ,因此它开始遍历列表中的每个文件名,直到完成。我只是想测试它的文件名'a.json'作为测试。然后我可以单独测试'b.json'和'c.json'。我目前得到的输出是:
a.json
()
(1000, 1000)
ok
b.json
()
(1000, 1000)
ok
c.json
()
(1000, 1000)
ok
所以伪代码将是:
For a.json in file_names
if a.json exists in jsonDatacurrFile
if a.json exist in both jsonDataprevFile and jsonDatacurrFile
use compare function with the filesize from jsonDatacurrFile and jsonDataprevFile for a.json and output whatever condition it meets
所以一个示例输出是:
a.json - ok
文件如下:
jsonDataprevFile 等于:
{"File Name": "a.json", "File Size": 1000}
{"File Name": "b.json", "File Size": 1000}
{"File Name": "c.json", "File Size": 1000}
jsonDatacurrFile
{"File Name": "a.json", "File Size": 1000}
{"File Name": "b.json", "File Size": 1000}
{"File Name": "c.json", "File Size": 1000}
我目前的逻辑如下:
def compare(previous,current):
# temporary for debug
print()
print(previous,current)
tolerance = 0.4
if previous is None and current is None:
return "both missing"
if previous is None:
return "new"
if current is None:
return "missing"
size_ratio = float(current)/previous
if size_ratio >= 1 + tolerance:
return "not ok %d%% bigger" % round(((size_ratio - 1) * 100),0)
if size_ratio <= 1 - tolerance:
return "not ok %d%% smaller" % round(((1 - size_ratio) * 100),0)
return "ok"
def readFileIntoDict(pathOfFile):
fo = open(pathOfFile, "rw+")
linesOfFiles = fo.readlines()
dataInFile = {}
for line in linesOfFiles:
jsonD = json.loads(line)
dataInFile[jsonD['File Name']] = jsonD['File Size']
return dataInFile
jsonDataprevFile = readFileIntoDict('dates/2018-01-01.json')
jsonDatacurrFile = readFileIntoDict('dates/2018-01-02.json')
file_names = ['a.json', 'b.json', 'c.json']
for fileNames in file_names:
if fileNames in jsonDatacurrFile:
if jsonDataprevFile[fileNames] == jsonDatacurrFile[fileNames]:
print fileNames
print(compare(jsonDataprevFile.get('a.json') , jsonDatacurrFile.get('a.json')))
【问题讨论】:
-
已修复@PatrickArtner
标签: python json python-2.7 list dictionary