A brief note on Files, Comprehensions and Generators: text files and their modes, lines as records, CSV and JSON, list, set and dictionary comprehensions, zip and enumerate, iterators, generators and pipelines. With a worked example, practice, a program and questions to check yourself.
A brief note on Files, Comprehensions and Generators. Read it before a test. Try each question at the end before you open its answer.
with open(name, mode) as f: opens a file, and always closes it at the end of the block.| Mode | What it does |
|---|---|
"r" | reads (the usual mode) |
"w" | writes, and empties the file first |
"a" | adds to the end |
write does not add a newline. Put \n at the end of each line yourself.\n. Use line.strip() before you compare.FileNotFoundError. Catch that error by name with try and except."w".csv.reader gives each row as a list; csv.DictReader gives a dictionary, with the header as keys. Open it with newline="".json.dump and json.load use files; json.dumps and json.loads use texts.True, False and None. A tuple comes back as a list, a number key comes back as text, and a set cannot be saved.[expression for item in iterable if condition] builds a new list in one line.if goes at the end. A choice, a if condition else b, goes at the front.{k: v for ...} builds a dictionary, and {e for ...} builds a set.zip pairs two lists and stops at the shorter one. enumerate gives a position with each item.any is True when one item passes, and all when every item passes. For an empty list, any is False and all is True.lambda x: expression is a short function with no name, handy as a key.for loop calls iter once, then next again and again, until StopIteration.yield is a generator. Calling it runs nothing yet; each next runs it to the next yield, where it pauses with its variables kept.(x * x for x in data), makes values one at a time, without building a list.itertools.islice takes the first few.What does this program show?
g = every_other(5) makes a generator, but runs none of its body. Nothing is printed yet.next runs the body from the top: it prints start, reaches yield 5, and pauses. 5 is printed.next continues after the yield: n becomes 3, and it yields 3.list(g) asks for every value left. It yields 1; then n becomes , the loop ends, done is printed, and the generator stops.The program shows start, 5, 3, done and [1], one on each line. The [1] comes last, because list must finish before print runs.
The program writes a small CSV file of rainfall, reads it through a generator that skips bad rows, and saves a summary as JSON.
"w" when you meant to add. The old text is gone. Use "a".row["mm"] + 5 stops with TypeError: can only concatenate str (not "int") to str. Convert with float() first.TypeError: Object of type set is not JSON serializable. Save a list.else at the end of a comprehension. [x for x in xs if x > 0 else 0] is a SyntaxError. A choice goes at the front: [x if x > 0 else 0 for x in xs].list() of an endless generator. It never ends. Use islice.diary.txt with "w" each morning and writes that day's line. After it has run on three mornings, how many lines does the file hold?{len(w) for w in ["ant", "bee", "wasp"]}, and why does it hold fewer values than the list of words?pairs = zip(["Ira", "Om", "Tia"], [88, 92]). What does list(pairs) give?g yields 2, 5 and 9, and then ends. A program runs total = sum(g) and then count = len(list(g)). What are total and count?[line.strip() for line in f] or (line.strip() for line in f)? Why?Log in to join the discussion.
Loading…