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
# The / joins the parts of a path
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.On a Windows computer, Python prints the same path with backslashes:
docs\reports\2023.txt, and the / in your code still works there. This site runs Python in your browser, so here it always shows /.from pathlib import Path
p = Path('saves') / 'slot1.json'
print(p.name) # slot1.json (the last part)
print(p.stem) # slot1 (the name, no ending)
print(p.suffix) # .json (the ending and its dot)Creating and Managing Files
from pathlib import Path
target = Path('output') / 'data.txt'
# Make the folder (target.parent), and any
# missing folders above it
target.parent.mkdir(parents=True, exist_ok=True)
# Write text to the file. If the file is
# already there, this replaces what it held.
# encoding='utf-8' saves letters like é and £
# the same way on every computer.
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 the files whose names match a pattern. In '*.txt', the * means anything, so it matches every name ending in .txt. It can return them in any order, so sort them when the order matters.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)
# The folder your code runs in. On this site,
# it's a new, empty folder for each run.
print(os.getcwd())
# Folders inside folders, like 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 the data into the file f, as JSON.
# indent=2 spreads it over several lines,
# with each key pushed in by two spaces.
with open('config.json', 'w') as f:
json.dump(data, f, indent=2)
# Read it back. No mode means read.
with open('config.json') as f:
loaded = json.load(f)
print(loaded)