Add lesson 7: Reading and writing files
3 changed files with 37 additions and 0 deletions
lessons/07-reading-and-writing-files/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 7: Reading and writing files | |
| 2 | + | |
| 3 | +We look at reading and writing files the way working developers use it, with examples you can change and run right away. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/python-basics/lessons/7](https://glibcode.net/courses/python-basics/lessons/7) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `files.py`: writing a file, reading it back line by line | |
| 10 | + | |
| 11 | +## Run it | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +python3 files.py | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## Exercises | |
| 18 | + | |
| 19 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/07-reading-and-writing-files/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 7 | |
| 2 | + | |
| 3 | +1. Time yourself: rewrite the example from memory in 10 minutes, then diff it against the original. | |
| 4 | +2. Look up one function or command the example uses in the official documentation. Note one option you didn't know. | |
| 5 | +3. Add a check that prints a warning when a result looks wrong (negative, empty, too big). | |
lessons/07-reading-and-writing-files/files.py ADDED
| @@ -0,0 +1,13 @@ | ||
| 1 | +from pathlib import Path | |
| 2 | + | |
| 3 | +notes = Path("notes.txt") | |
| 4 | +notes.write_text("buy milk\ncall grandma\nfinish lesson 7\n") | |
| 5 | + | |
| 6 | +with notes.open() as f: | |
| 7 | + for number, line in enumerate(f, start=1): | |
| 8 | + print(number, line.strip()) | |
| 9 | + | |
| 10 | +# append instead of overwriting | |
| 11 | +with notes.open("a") as f: | |
| 12 | + f.write("water the plants\n") | |
| 13 | +print(notes.read_text().count("\n"), "lines now") | |