python - 如何在 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)
不工作。
解决方案
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)
推荐阅读
- c# - 在 TDD 中使用调解器 cqrs 进行集成测试 .net core 3
- typescript - 推断通用的“this”类型
- javascript - 为什么此代码返回未定义以及如何使此代码工作
- json - 评估表达式 json 结果在调试模式下与最终 json 结果不同
- python - PyTesseract 导致 PIL 引发 ValueError: tile cannot extend outside image
- javascript - 根据长度递归地将元素添加到数组中
- c# - 唱歌时如何将 UserID 存储在班级中?
- bash - Bash:make:即使在安装 msys-make 软件包后也找不到命令
- c# - 实体映射:将两个属性引用到外键时出现问题
- javascript - 如何将列表显示为 lg 屏幕的 3 列和 sm 屏幕的 1 列