首页 > 解决方案 > 如何在 python 中将打印语句写入 csv 文件?

问题描述

我有一个关于一些动物统计数据的数据集。其中 cat_teeth、dog_teeth、horse_teeth 和 numfeet 变量都是整数。

            print(“Cat”,sum(cat_teeth), cat_numfeet)
            print(“Dog”,sum(dog_teeth), dog_numfeet)
            print(“Horse”,sum(horse_teeth), horse_numfeet)

上面的代码给了我

Cat 38 4
Dog 21 4
Horse 28 4

我希望将相同的输出导出到一个 csv 文件,其中有 3 列,如上所示,由逗号 (,) 分隔。

我该怎么做?

import csv 
    with open(“results.csv”, “w”) as csvfile:
    writer= csv.writer(csvfile)
    

    writer.writerow(“Cat”,sum(cat_teeth), cat_numfeet))
    writer.writerow(“Dog”,sum(dog_teeth), dog_numfeet)     
    writer.writerow(“Horse”,sum(horse_teeth), horse_numfeet)

不工作。

标签: pythonnumpy

解决方案


If you want to use print instead of writerow, this is how I would do.

import csv 
with open("results.csv", "w") as csvfile:
    print("Animal, cat_teeth, cat_numfeet", file=csvfile)
    print(f"Cat, {sum(cat_teeth)}, {cat_numfeet}", file=csvfile)
    print(f"Dog,{sum(dog_teeth)}, {dog_numfeet}", file=csvfile)
    print(f"Horse,{sum(horse_teeth)}, {horse_numfeet}", file=csvfile)

推荐阅读