今天我在python dict中发现了问题。我需要从循环中收集所有输出数据并将其写入json文件中。编写过程运行良好,但结果,在json文件中只有一个,最后一个输出。我应该如何使用字典修复部分代码?这是代码:
def classify(sess, label_list, softmax_output, coder, images, image_file):
print('Running file %s' % image_file)
image_batch = make_batch(image_file, coder, not FLAGS.single_look)
batch_results = sess.run(softmax_output, feed_dict={images:image_batch.eval()})
output = batch_results[0]
batch_sz = batch_results.shape[0]
for i in range(1, batch_sz):
output = output + batch_results[i]
output /= batch_sz
best = np.argmax(output)
best_choice = (label_list[best], output[best])
Guess = 'Guess @ 1 %s, prob = %.2f' % best_choice
print('Guess @ 1 %s, prob = %.2f' % best_choice)
faces_pred = dict()
faces_pred = {"face_pred": Guess}
with open('pred.json', 'w') as fp:
json.dump( faces_pred, fp)
nlabels = len(label_list)
if nlabels > 2:
output[best] = 0
second_best = np.argmax(output)
print('Guess @ 2 %s, prob = %.2f' % (label_list[second_best], output[second_best]))
return best_choice
我只对Guess 1的所有输出感兴趣! 谢谢您的时间:3
UPD --------- 在json文件里面,运行我的程序后,输出:
{"face_pred": "Guess @ 1 (60, 100), prob = 0.75"}
这是正确的,但只适用于一张脸(我有3+猜猜@ 1)。它没有在json文件中添加新数据,只是重写它!
UPD2 -------- 控制台的外观如何:
答案 0 :(得分:1)
您的评论我现在明白您的问题...您打开文件如下:
with open('pred.json', 'w') as fp:
json.dump( faces_pred, fp)
并且每次都重写整个文件,因此您只能获得最后的结果
你可以这样做:
with open('pred.json', 'a') as fp:
data_to_write = json.dumps(faces_pred)
fp.write(faces_pred + '\n')
注意我在这里做的两件事:
我用' a'打开了文件。标记而不是' w',每次用于附加到文件末尾而不是重写文件
我使用json.dumps
代替json.dump
来生成字符串,然后将该字符串(附加)写入文件,最后使用\n
来确保它每次都会打破这一行