From 7a4af42cc16c78360a71cdb1ace481bf3c68cead Mon Sep 17 00:00:00 2001 From: waldek Date: Fri, 12 Nov 2021 11:08:23 +0100 Subject: [PATCH] adds csv --- learning_python3.md | 49 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/learning_python3.md b/learning_python3.md index 3bd4f99..a4bbc54 100644 --- a/learning_python3.md +++ b/learning_python3.md @@ -1825,7 +1825,54 @@ We already saw a dictionaries which are good mapping structures but how can we s A hacky way would be to write a python file containing the `dict` and `import` it when we need it. But there are better ways. -**TODO CSV** +The table below probably makes you think of *excel*. +We can use excel to create a text based **database** where the first line, called the **header**, defines what information is stored in the database. +Every **row** after the header is an **entry** with the item's values. +Sounds more complicated than it is. + +| description | urgency | done | +|-------------------------------|---------|------| +| go to the shops | 9 | 0 | +| install music computer | 4 | 0 | +| download python documentation | 7 | 1 | +| bottle new beer | 9 | 1 | + + +We can *convert* this table to a **Comma Separated Value** file, which can easily be read by python. + +```csv +description,urgency,done +go to the shops,9,0 +install music computer,4,0 +download python documentation,7,1 +bottle new beer,9,1 +``` + +If we save this to a blank file we can us the built-in `open` function to read and interpret the data as a `list` of `dict`. +The code below does exactly that, first without list comprehension, secondly with. + +```python +import csv + +with open("./data.csv", "r") as fp: + tasks = csv.DictReader(fp) + print(tasks) + for task in tasks: + print(task) + + +with open("./data.csv", "r") as fp: + tasks = [task for task in csv.DictReader(fp)] + +print(tasks) +``` + +🏃 Try it +--- + +Adapt your task manager to read tasks for a CSV file. +Implement the urgency to sort your tasks by importance. +Don't delete tasks from the file but rather mark them as *done*. # Now for some useful scripting