Summer Deals - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Writing CSV files
Summary

Instruction

Well done! Finally, it's time to put everything together. We're going to read data from one csv file, analyze its contents, and save the results into another csv file.

Suppose we've implemented a system to manage credit cards. The system_logs.csv file contains all logs from our application:

log_level,message
INFO,New card added.
INFO,New user created.
ERROR,Attempt to delete another user's card.
...

We want to analyze the contents of this file, get all possible log_levels, and count the number of logs with a given log level. As a result, we want to create a logs_report.csv file that will provide all unique logging levels together with the number of logs on that level. For instance:

INFO,21
ERROR,17
...

Exercise

Run the template code. Study the contents of the code and the output file.

First, we create an empty dictionary. We will use this dictionary in the following way: each key will be a unique log level from the input file, and its corresponding value will be an integer indicating how many logs were found in the input file at that given level.

Next, we open the input file using a DictReader (you can use csv.reader if you prefer) and read it line by line. For each line, we check whether the value in the log_level field is already present as a key in the log_levels dictionary. If it is, then we increment the key's value by 1. If it is not, this means we've found a new unique logging level. In that case, we add the logging level as a new key in the dictionary and assign an initial value of 1 to it.