Lesson 10
I am Your Father
Chapter 7: More file handling
Writing to CSV files
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.
1 2 3 4 5 6 7 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |