简体   繁体   中英

How to write print statements to csv file in python?

I have a dataset about some animal statistics. Where cat_teeth, dog_teeth, horse_teeth, and the numfeet variables are all integers.

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

The code above gives me

Cat 38 4
Dog 21 4
Horse 28 4

I want that same output exported to a csv file where there are 3 columns as shown above deliminated by a comma (,).

How would I do that?

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)

Does not work.

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)

writerow takes exactly one argument. Convert the values to a list and then call the function.

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

Put the items into a list, don't pass them as separate arguments. Also, don't use a text editor to write your code, since those weird quotes “” will probably break stuff. Use an IDE like Pycharm.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM