Jo Ko
Jo Ko

Reputation: 7575

Python: How to write a CSV file?

I would like to write a CSV that outputs the following:

John
Titles    Values
color     black
age       15

Laly
Titles    Values
color     pink
age       20

total age 35

And so far have:

import csv

students_file = open(‘./students_file’, ‘w’)
file_writer = csv.DictWriter(students_file)

…

file_writer.writeheader(name_title) #John
file_writer.writeheader(‘Titles’:’Values’)
file_writer.writerow(color_title:color_val) #In first column: color, in second column: black
file_writer.writerow(age_title:age_val) #In first column: age, in second column: 15
file_writer.writerow('total age': total_val) #In first column: 'total age', in second column: total_val

But seems like it just writes on new rows rather than putting corresponding values next to each other.

What is the proper way of creating the example above?

Upvotes: 0

Views: 107

Answers (1)

user657127
user657127

Reputation:

I don't think you got the concept of .csv right. The c stands for comma (or any other delimiter). I guess it means Comma,Separated,Values.

Think of it as an excel sheet or a relational database table (eg. MySQL).

Mostly the document starts with a line of col names, then the values follow. You are not in need to write eg. age twice.

Example structure of a .csv

firstname,lastname,age,favorite_meal
Jim,Joker,33,"fried hamster"
Bert,Uber,19,"salad, vegan"

Often text is enclosed in " to, so that itself can contain commas and dont't disturb your .csv structure.

Upvotes: 2

Related Questions