You have been using
open() with string paths. That works, but the pathlib module gives you a cleaner object-oriented way to handle file locations.The Path Object
from pathlib import Path
# Joining parts is as simple as using the / operator
target = Path('docs') / 'reports' / '2023.txt'
print(target)Path objects let you inspect and manipulate paths without string concatenation. You can extract specific parts of the path using attributes.from pathlib import Path
p = Path('notes') / 'day1.txt'
print(p.name) # day1.txt (the last part)
print(p.stem) # day1 (name without extension)
print(p.suffix) # .txt (extension with the dot)Creating and Managing Files
from pathlib import Path
target = Path('output') / 'data.txt'
# Create the folder if it doesn't exist (including parents)
target.parent.mkdir(parents=True, exist_ok=True)
# Write text directly to the file
target.write_text('Hello from pathlib!\n', encoding='utf-8')
# Check if a path exists on disk
print(target.exists()) # True
# Read it back
content = target.read_text(encoding='utf-8')
print(content)Path.glob() finds files matching a pattern. The order is not guaranteed, so always sort the result if you need consistency.from pathlib import Path
import os
os.makedirs('docs', exist_ok=True)
(Path('docs') / 'a.txt').write_text('A')
(Path('docs') / 'b.md').write_text('B')
# Find all .txt files in docs/
txt_files = sorted(Path('docs').glob('*.txt'))
print([f.name for f in txt_files]) # ['a.txt']The Classic os and glob Modules
import os
import glob
# Equivalent to Path('docs') / 'a.txt'
path = os.path.join('docs', 'a.txt')
print(path)
# Current working directory
print(os.getcwd())
# Create nested folders (equivalent to mkdir(parents=True))
os.makedirs('logs/2023/jan', exist_ok=True)
# Every .txt file in the current folder
files = sorted(glob.glob('*.txt'))Saving Python Data to Files
import json
data = {'name': 'Pythos', 'version': 2}
# Write JSON directly to a file (dump with an f)
with open('config.json', 'w') as f:
json.dump(data, f, indent=2) # pretty-printed output
# Read it back into a Python object (load from an f)
with open('config.json', 'r') as f:
loaded = json.load(f)
print(loaded)