L5·Intermediate/Advanced

🗂️Pathlib & File I/O

Modern paths and safe file handling.

pathlibopenwith

§ 1Path objects

from pathlib import Path. p / 'sub' / 'file.txt' composes paths. .exists(), .is_file(), .read_text(), .write_text().

§ 2open()

open(path, mode) with mode 'r', 'w', 'a', 'rb', 'wb'. Always use inside with.

Example

1from pathlib import Path
2p = Path("greeting.txt")
3p.write_text("Hello!\n")
4print(p.read_text())

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
Path('a') / 'b' returns: