Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Python Programming home

Department of Computing, Imperial College London

Python for C++ Programmers


Chapter 1: Introduction
Chapter 2: Basic data types
Chapter 3: Variables and operators
Chapter 4: Sequence types
Chapter 5: Sets and dictionaries
Chapter 6: Control flow
Chapter 7: Functions
Chapter 8: Object-oriented programming
Chapter 9: Modules
Chapter 10: Files
[10.1] Handling text files
[10.2] JSON files
[10.3] Loading JSON files
[10.4] Writing to JSON files
[10.5] pickle
[10.6] Pickling time!
[10.7] CSV files
[10.8] Reading CSV files
[10.9] Reading CSV files into a dict
[10.10] Writing to CSV files
[10.11] That's a wrap!

Chapter 10: Files


>> Writing to CSV files
face Josiah Wang

You can write data to a CSV file with the writer object in the csv module.
Use the .writerow() method to write a single row.
Use the .writerows() method to write multiple rows in one go.
The following code should produce a CSV file with the same content as our original students.csv from before.
import csv

header = ["name", "faculty", "department"]

data = [
["Alice Smith", "Science", "Chemistry"],
["Ben Williams", "Eng", "EEE"],
["Bob Jones", "Science", "Physics"],
1 ["Andrew Taylor", "Eng", "Computing"]
2 ]
3
4 with open("output_students.csv", "w") as csv_file:
5 writer = csv.writer(csv_file)
6 writer.writerow(header)
7 writer.writerows(data)
8
9
10
11
12
13
14
15

Writing to CSV files from a dictionary


You can also write to a CSV file from a dict rather than a list. Useful if you already have your object represented as
a structured dict.
Like csv.writer above, you can write a single dictionary with .writerow() or a list of dictionaries with .writerows().
Note the new .writeheader() method in the code below! Just for the sake of it, the code also demonstrates writing
a CSV separated by | instead of commas.
import csv

header = ["name", "faculty", "department"]

data = [
{"name": "Alice Smith", "faculty": "Science", "department": "Chemistry"},
{"name": "Ben Williams", "faculty": "Eng", "department": "EEE"},
1 {"name": "Bob Jones", "faculty": "Science", "department": "Physics"}
2 ]
3
4 extra_student = {"name": "Andrew Taylor",
5 "faculty": "Eng",
6 "department": "Computing"}
7
8 with open("output_students.csv", "w") as csv_file:
9 writer = csv.DictWriter(csv_file, fieldnames=header,
10 delimiter="|")
11 writer.writeheader()
12 writer.writerows(data)
13 writer.writerow(extra_student)
14
15
16
17
18
19
20

Previous Next 

Page designed by Josiah Wang Department of Computing | Imperial College London

You might also like