简体   繁体   中英

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?

I don't think you got the concept of .csv right. The c stands for comma (or any other delimiter). I guess it means C omma, S eparated, V alues.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM