0

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]

nikamoon
  • 1
  • 1
  • 1
    Does this answer your question? [How do I read and write CSV files with Python?](https://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python) – Christopher Peisert Oct 17 '20 at 15:27
  • Normally `my_row` would be a list of values, with each element in the list corresponding to a cell. Your list appears to contain a single string with a comma in it. Is that really what you want? As opposed to `my_row = [item, means[item]]`? – Tom Karzes Oct 17 '20 at 15:29
  • 1
    You left out crucial details. What are `names` and `means`? And yank that line `mean_writer=csv.writer(ff)` out of the loop. –  Oct 17 '20 at 15:29

2 Answers2

1

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)
Aniket Tiratkar
  • 798
  • 6
  • 16
dev0
  • 50
  • 1
  • 8
0

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')
marsolmos
  • 748
  • 9
  • 24