Python csvwriter未写入csv文件

时间:2019-02-06 11:09:56

标签: python csv tensorflow

我是python新手,csv模块有问题。

我的代码成功创建了csv文件,但csv文件仍然为空。

这是我的代码:

with open('log.csv', 'w') as stream:
    csvwriter = csv.writer(stream, delimiter=',', quotechar='"')

    for i in range(0, 200):
        model.train(input_fn=train_input_fn, steps=100)
        evaluation_result = model.evaluate(input_fn=test_input_fn)

        predictions = list(model.predict(input_fn=test_input_fn))
        prediction_result = betting.test_betting_stategy(predictions, test_features, test_labels)

        csvwriter.writerow([(i + 1) * 100, evaluation_result['accuracy'], evaluation_result['average_loss'], prediction_result['performance']])
stream.close()    

我的问题是如何使python刷新到磁盘并写入csv文件?

2 个答案:

答案 0 :(得分:0)

stream.flush()之后使用csvwriter.writerow()

Same question

答案 1 :(得分:0)

好。正如我所说的,我是python的新手,现在我获得了缩进的价值。

以下代码很完美。

with open('log.csv', 'w') as stream:
csvwriter = csv.writer(stream, delimiter=',', quotechar='"')

for i in range(0, 200):
    model.train(input_fn=train_input_fn, steps=100)
    evaluation_result = model.evaluate(input_fn=test_input_fn)

    predictions = list(model.predict(input_fn=test_input_fn))
    prediction_result = betting.test_betting_stategy(predictions, test_features, test_labels)

    csvwriter.writerow([(i + 1) * 100, evaluation_result['accuracy'], evaluation_result['average_loss'], prediction_result['performance']])
    stream.flush() **#This indentation works perfectly!!!**