Python Pages Doc Ic Ac Uk CPP Lessons CPP 10 Files 10 Csvwrite HTML
Python Pages Doc Ic Ac Uk CPP Lessons CPP 10 Files 10 Csvwrite HTML
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
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
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