Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
CSV dialects
7. Registering new dialects
Summary

Instruction

Good job! Naturally, you can also register new dialects. Take a look:

import csv
csv.register_dialect('pipes', delimiter='|')

The first parameter in the csv.register_dialect() method is the name we want to give to our new dialect. Then, we can specify as many parameter values as we want. If we don't provide a value for some parameters, their default values will be used instead. The default values are as follows:

quotechar: "
delimiter: ,
doublequote: True
escapechar: None
lineterminator: \r\n
quoting: QUOTE_MINIMAL
skipinitialspace: False

Once you register a new CSV dialect, you can use it to read and write CSV files just like any other dialect:

with open('filename.csv', mode='w', newline='') as csv_file:
  csv_writer = csv.writer(csv_file, dialect='pipes')

Exercise

Create a CSV dialect named 'slashes'. It should use a forward slash (/) as the delimiter and a single quote (') as the quotechar. It should also use QUOTE_ALL for quoting. All the other parameters should have their default values.

We've written proper prints for you to see what the new dialect looks like. To get the properties of our custom dialect, we've used the get_dialect() function.

Stuck? Here's a hint!

Use the following code:

csv.register_dialect('slashes', delimiter='/', quotechar="'", quoting=csv.QUOTE_ALL)