And keep in mind that Path objects are accept nearly anywhere a string-representing-a-path is accepted.
>>> with open(path) as f:
... for line in f:
... print(line.rstrip())
...
Even utilities like subprocess.run and shutil.move accept Path-like objects.
๐บ This pathlib infomercial was brought to you by
โข A need to work with file paths in Python
โข, My dislike of awkwardly nested function calls
โข, An appreciation for using concrete objects instead of just passing strings around everywhere
I keep seeing replies about how Path objects need to be converted to strings to actually use them. This was true (& was the reason I didn't like pathlib in Python 3.4), but it's not true anymore.
Let's talk about what these methods do and why I recommend these ones first. ๐งต
1๏ธโฃ The string join method accepts an iterable of strings to join together.
It should be called on the separator you'd like to join by (e.g. " ", "\n", ",", ""). This is a string method: it's " ".join(my_list) and not my_list.join(" ").
While teaching comprehensions I sometimes see students do this:
numbers = [2, 1, 3, 4, 7, 11]
squares = []
[squares.append(n**2) for n in numbers]
Comprehensions are for building up a new list, but that one above actually builds up *two* new lists. ๐งต
From a Python prompt, you can see what's going on:
>>> [squares.append(n**2) for n in numbers]
[None, None, None, None, None, None]
Comprehensions return a new list and the items in that list come from that first expression in the comprehension. squares.append returns None. ๐ฆ
We *do* modify the squares list:
>>> squares
[4, 1, 9, 16, 49, 121]
But that's a side effect, which comprehensions aren't supposed to have. Here's another comprehension with a side effect:
>>> [print(n**2) for n in numbers]
4
1
9
16
49
121
[None, None, None, None, None, None]
In Python, variables and data structures don't "contain" objects.
This idea is easy to miss when new to Python and it can be hard to internalize.
Let's talk about this. ๐งต
Note: "value" and "object" are synonyms in this thread and so are "variable" and "name".
Variables in Python aren't "buckets containing things" but "pointers" (they point to values). The word pointer may sound scary (it is scary in C), but it mostly means what it sounds like.
An arrow connects each variable to a value and 2 variables can point to the same value. โก
Assignment statements point a variable to a value. That's it. Python doesn't copy anything when you assign.
So this is an odd thing to do:
>>> x = y
Because we've pointed two names to the same value. So what? Why does that matter? ๐ค