Skip to content

Latest commit

 

History

History
131 lines (99 loc) · 1.44 KB

20230824175324.md

File metadata and controls

131 lines (99 loc) · 1.44 KB

os vs pathlib

🚀 10 useful things you can do more easily (and therefor Pythonically) with pathlib than os 🐍

1️⃣ Creating/Joining Paths:

os:

p = os.path.join('folder', 'file.txt')

pathlib:

p = Path('folder') / "file.txt"

2️⃣ Getting Home Dir:

os:

home = os.path.expanduser("~")

pathlib:

home = Path.home()

3️⃣ Getting Path's Name without Suffix:

os:

name = os.path.splitext(os.path.basename(p))[0]

pathlib:

name = p.stem

4️⃣ Getting File Extension:

os:

ext = os.path.splitext(p)[-1]

pathlib:

ext = p.suffix

5️⃣ Reading & Writing Text:

os:
with open(p, 'r') as f:
    content = f.read()
with open(p, 'w') as f:
    f.write("Hello!")

pathlib:

content = p.read_text()
p.write_text("Hello!")

6️⃣ Iterating Over Directory Contents:

os:

children = os.listdir(p)

pathlib:

children = list(p.iterdir())

7️⃣ Making Directories:

os:

if not os.path.exists(p):
    os.makedirs(p)

pathlib:

p.mkdir(parents=True, exist_ok=True)

8️⃣ Changing File Suffix:

os:

base, _ = os.path.splitext(p)
new_p = base + '.md'

pathlib:

new_p = p.with_suffix('.md')

9️⃣ Getting Absolute Path:

os:

abs_path = os.path.abspath(p)

pathlib:

abs_path = p.resolve()

🔟 Getting the Parent Directory:

os:

parent_dir = os.path.dirname(p)

pathlib:

parent_dir = p.parent

#pathlib