adds csv
This commit is contained in:
		
							parent
							
								
									4ca8debe0d
								
							
						
					
					
						commit
						7a4af42cc1
					
				| 
						 | 
				
			
			@ -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
 | 
			
		||||
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
		Loading…
	
		Reference in New Issue