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)