nikamoon
nikamoon

Reputation: 1

writing in csv file

It's the first time I want to write in a CSV file and there are some strings I want to write as output. I used 'writerow' function but it writes them in list type while I simply want them to be strings has anyone have any idea what should I do?

my code:

with open (r'C:\Users\part pardaz\Desktop\out_put.csv' , mode='w' , newline='' ) as ff : 
    mean_writer=csv.writer(ff)
    for  item in (names):
    print(item)      
    my_row=[item + ',' + means[item] ]
    print(my_row)
    mean_writer.writerow((my_row))

I want my output to be like this:

jack,23

mike,76

but it's like this:

[jack,23]

[mike,76]

Upvotes: 0

Views: 96

Answers (2)

dev0
dev0

Reputation: 50

There are couple things wrong with the code, please put csv.writer out of your for loop.

Try this code below before you try yours.

import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

Also try replacing:

mean_writer.writerow((my_row))

with

mean_writer.writerow(my_row)

Upvotes: 1

marsolmos
marsolmos

Reputation: 794

You can use pandas library, and then just make use of pandas read_csv and to_csv functions. Something like:

import pandas as pd

df = pd.read_csv('path/to/csv')
# do some stuff with the loaded csv
df.to_csv('path/to/csv')

Upvotes: 0

Related Questions