Skip to content

Managing Paths with pathlib

Why pathlib

pathlibpathlib gives you:

  • operator-free path joining
  • clear methods (existsexists, is_fileis_file, mkdirmkdir, read_textread_text)
  • cross-platform behavior

Common patterns

pathlib_basics.py
from pathlib import Path
 
base = Path.home() / "Downloads"
print(base)
 
for f in base.iterdir():
    if f.is_file():
        print(f.name, f.suffix)
pathlib_basics.py
from pathlib import Path
 
base = Path.home() / "Downloads"
print(base)
 
for f in base.iterdir():
    if f.is_file():
        print(f.name, f.suffix)

Reading and writing

pathlib_read_write.py
from pathlib import Path
 
p = Path("hello.txt")
p.write_text("hello\n", encoding="utf-8")
print(p.read_text(encoding="utf-8"))
pathlib_read_write.py
from pathlib import Path
 
p = Path("hello.txt")
p.write_text("hello\n", encoding="utf-8")
print(p.read_text(encoding="utf-8"))

๐Ÿงช Try It Yourself

Exercise 1 โ€“ List Files with os.listdir

Exercise 2 โ€“ Join Paths with os.path.join

Exercise 3 โ€“ Write and Read a File

If this helped you, consider buying me a coffee โ˜•

Buy me a coffee

Was this page helpful?

Let us know how we did