#TIL #pathlib.Path in #python can not only lead the `Path('.') / file`, bu be at any place in the expression
In [42]: 'tmp' / Path('build_report_some_name.json')
Out[42]: PosixPath('tmp/build_report_some_name.json')
In [43]: 'tmp' / Path('build_report_some_name.json') / 'some_another_part'
Out[43]: PosixPath('tmp/build_report_some_name.json/some_another_part')
I get not liking the "clever" overloading of the division operator. Luckily, you don't have to use it - you can pass a full path as a single string, or a list of strings, and it will Do The Right Thing:
>>> Path("/usr", "lib", "grub")
PosixPath('/usr/lib/grub')
>>> Path("/usr/lib/grub")
PosixPath('/usr/lib/grub')
pathlib is nice because it gives some better, high-level abstractions. Things like `path.relative_to(other_path)` are very natural to read.
[...]
Day 3,406 of wishing Python's tempfile module returned pathlib.Path objects instead of str.
In a a recent #Python (3.6) program used "#pathlib.Path" to munge paths. It was a pleasant change from the #eye_poking "str.join" and (fair) "str.split" functions.
@brettcannon @nedbat Nice (for "[#pathlib] picking up os.walk()"), as I had wanted that in it in #python 3.{[89],10} not too long ago.
@brettcannon thanks for your work on pathlib!
I used that just yesterday in a project instead of os.path.
#python #pathlib #thankadeveloper
RT @treyhunner@twitter.com
Before #pathlib
import glob
code = []
for name in glob.iglob('**/*.py', recursive=True):
with open(name) as py_f:
code.append(py_f.read())
After ✨
from pathlib import Path
code = [
http://path.read_text()
for path in Path.cwd().rglob('*.py')
]
🐦🔗: https://twitter.com/treyhunner/status/1562907453750095873
RT @treyhunner@twitter.com
Before #pathlib
import os.path
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')
After ✨
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = BASE_DIR / 'templates'
🐦🔗: https://twitter.com/treyhunner/status/1560370741551456256
Before #pathlib
import glob
code = []
for name in glob.iglob('**/*.py', recursive=True):
with open(name) as py_f:
code.append(py_f.read())
After ✨
from pathlib import Path
code = [
http://path.read_text()
for path in Path.cwd().rglob('*.py')
]
Before #pathlib
import os.path
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')
After ✨
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATES_DIR = BASE_DIR / 'templates'
RT @python_tip@twitter.com
#pathlib Path.stat().st_size prints size of the file in bytes
https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat
🐦🔗: https://twitter.com/python_tip/status/1207578845890699264