簡體   English   中英

如何在python中將打印語句寫入csv文件?

[英]How to write print statements to csv file in python?

我有一個關於一些動物統計數據的數據集。 其中 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)

不起作用。

如果你想使用print而不是writerow ,這就是我會做的。

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)

writerow接受一個參數。 將值轉換為列表,然后調用該函數。

writer.writerow(["Cat",sum(cat_teeth), cat_numfeet])

將項目放入列表中,不要將它們作為單獨的參數傳遞。 另外,不要使用文本編輯器來編寫代碼,因為那些奇怪的引號“”可能會破壞內容。 使用像 Pycharm 這樣的 IDE。

writer.writerow(["Cat", sum(cat_teeth), cat_numfeet)])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM