0

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?

6
  • 1
    I would recommend having a look at this: pandas.pydata.org/pandas-docs/stable/generated/…... Using pandas is really good in most such cases Commented Mar 31, 2017 at 18:45
  • 2
    I don't think you got the concept of .csv right. The c stands for comma (or any other delimiter). Think of it as an excel sheet. First line with the col names, then the values. You are not in need to write eg. age twice. Commented Mar 31, 2017 at 18:49
  • @ansi_lumen Appreciate the response. Aware that it's an excel sheet. In the excel sheet, would like to create the example. Do you mind putting it as an answer? So that I can upvote/accept as well. Commented Mar 31, 2017 at 18:59
  • It is Excel like in a more restricted way. Just the column fashion, with header just in the first line. Commented Mar 31, 2017 at 19:22
  • @LaurentG Can you show an example? Commented Mar 31, 2017 at 21:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.