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

Instruction

Perfect! As we noted in Part 1, there is no standard for what delimiter a CSV must use, even though the name suggests that commas are the most popular option.

Fortunately, you can specify optional parameters for both csv.reader() and csv.DictReader(), the most useful of which is delimiter. Take a look:

import csv
with open('departments_semicolons.csv') as csv_file:
  csv_reader = csv.DictReader(csv_file, delimiter=';')
  ...

We introduced an optional delimiter parameter that equals the semicolon character. This means we expect the CSV file to use semicolons rather than commas to separate its fields.

Exercise

You are given a CSV file named houses.csv with monthly rent prices for selected properties. You can check its contents in the Datasets tab. Semicolons are used as delimiters in this file. Your task is to calculate and print the average rent price of this set of properties.

Stuck? Here's a hint!

Use delimiter=';' for csv.DictReader(). Sum all rent prices in a loop. At the same time, keep track of the number of lines. Finally, divide the sum of house rent prices by the number of houses.