Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Reading CSV files
9. Changing the quote character
Summary

Instruction

Very well done! Imagine you have a CSV file that uses its delimiter as part of the field. Let's look at this classic sentence (that uses a comma):

Hello, World!

If we wrote that down in a CSV file simply as it is, with a comma as our delimiter, we would end up with something like this:

id,sentence
1,Hello, World!

And this will cause us to have three columns in the second row! So we'll fix it by quoting the sentence, let's say with ':

id,sentence
1,'Hello, World!'

Now, we'll tell Python that we quote our values (look at the bold piece below):

import csv
with open('sentences.csv') as csv_file:
  csv_reader = csv.DictReader(csv_file, quotechar="'")
...

Note: the default value for quotechar is ".

You may be thinking "Wait... What if we have a quote in our sentence? It will unquote it!" And you'd be right! We need to double those quotes (as in the second sentence here):

id,sentence
1,'Hello, World!'
2,'Who in the world am I? Ah, that''s the great puzzle'
3,Curiouser and curiouser

Note that we skipped quoting in the last sentence – it's unnecessary because there isn't any delimiter in that string.

Exercise

You are given a CSV file named sentences.csv. It uses semicolons as delimiters and single quotes as quote characters. Your task is to identify the longest sentence in the file and print its ID and contents in the following format:

{id}: {sentence}

Stuck? Here's a hint!

To parse the file, use:

csv.DictReader(csv_file, delimiter=';', quotechar="'")