如何将结果从屏幕输出保存到python中2列的csv文件中?

时间:2019-03-11 16:24:28

标签: python python-3.x csv

import pandas as pd
import numpy as np
import csv

with open('predictions.csv', 'r') as f:
    csvreader = csv.reader(f)
    next(csvreader)
    for r in csvreader:
        df = r[:-1]
        a = float(str(df[:][0]))
        b = float(str(df[:][1]))
        if a > b :
            print(1, 0)
        else:
            print(0, 1)

0 1
0 1
0 1
0 1
0 1
0 1

我从predictions.csv文件中打印了我的结果,并且试图将结果显示为0和1,并保存到2列CSV文件中。那么如何将结果保存到显示的2列CSV文件中?

1 个答案:

答案 0 :(得分:1)

您不必保存打印输出-在循环中打印数据时,可以将数据直接保存为CSV,如下所示:

with open('new_file.csv', mode='a', newline='') as file:
    csv_writer = csv.writer(file)
    if a > b :
        print(1, 0)
        csv_writer.writerow(['1', '0'])
    else:
        print(0, 1)
        csv_writer.writerow(['0', '1'])