2

I have this kind of string output:

Gender,Age,Weight,Height
Male, 55, 82, 180
Female, 34,55,167
Female,44,67,182
Male,81,73,175
Male,44,34,87,185

What is the easiest way to make CSV file from this output? I tried some StringIO methods but I can't get them work in Python 3.6.0.

Juho M
  • 349
  • 2
  • 9
  • 19

4 Answers4

5

First Approach: Use StringIO

Here is my approach, which I tested against Python 3.6:

import csv
from io import StringIO

my_string = """
Gender,Age,Weight,Height
Male, 55, 82, 180
Female, 34,55,167
Female,44,67,182
Male,81,73,175
Male,44,34,87,185
"""

buffer = StringIO(my_string)

reader = csv.reader(buffer, skipinitialspace=True)
with open('string2csv.csv', 'w') as out_file:
    writer = csv.writer(out_file)
    writer.writerows(reader)

Contents of string2csv.csv file:

Gender,Age,Weight,Height
Male,55,82,180
Female,34,55,167
Female,44,67,182
Male,81,73,175
Male,44,34,87,185

Notes

  • Since the input string has spaces after comma (in other word, initial spaces before an entry), I am using the skipinitialspace=True argument to strip these spaces off.
  • By using writerows (plural) instead of writerow (singular), I am able to write less code

Second Approach: Split Lines

If you don't want to use StringIO, then we can split the lines, feed them into csv.reader and achieve the same result:

my_string = """
Gender,Age,Weight,Height
Male, 55, 82, 180
Female, 34,55,167
Female,44,67,182
Male,81,73,175
Male,44,34,87,185
"""
reader = csv.reader(my_string.splitlines(), skipinitialspace=True)
with open('string2csv.csv', 'w') as out_file:
    writer = csv.writer(out_file)
    writer.writerows(reader)
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • For those that read the posted solution, the next problem you are going to face is that `""` final new line in the end of the csv which you could remove by replacing `writer.writerows(reader)` with a for loop like this `for row in reader: if row == [""]: continue writer.writerow(row)`. Sorry for bad identation – Kots May 09 '22 at 16:14
3

assuming you have this string in a list, why not directly write to a file

>>> f = file('test.csv', 'w')
>>> lines = [ 'Gender,Age,Weight,Height',
    'Male, 55, 82, 180',
    'Female, 34,55,167',
    'Female,44,67,182',
    'Male,81,73,175',
    'Male,44,34,87,185']
>>> f.write('\n'.join(lines))
>>> f.flush()
>>> f.close()
saikumarm
  • 1,565
  • 1
  • 15
  • 30
0

I have this kind of string output.

Let's assume that the string name is data.

import StringIO
import csv

data = """Gender,Age,Weight,Height
Male, 55, 82, 180
Female, 34,55,167
Female,44,67,182
Male,81,73,175
Male,44,34,87,185"""

f = StringIO.StringIO(data)
reader = csv.reader(f, delimiter=',')

myfile = open('output.csv', 'wb')
writer = csv.writer(myfile, quoting=csv.QUOTE_ALL)

for row in reader:
    print '\t'.join(row)
    writer.writerow(row)
Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
0

You can used pandas and the data frame to do this :

df = { 'Gender' : pd.Series(['Male', 'Female', 'Female', 'Male', 'Male']), 
       'Age' : pd.Series([55, 34, 44, 81, 44]), 
      'Weight' : pd.Series([82, 55, 67, 73, 87]), 
      'Height' : pd.Series([180, 167, 182, 175, 185])}
df = pd.DataFrame(df)

df.to_csv('my_file.csv', '\t')
Chris PERE
  • 722
  • 7
  • 13