Legends ofPythos
Claim your name
The Standard Library

Files and folders

Lesson 2 of 7

Watch the lesson5:37 · with Torsten
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)
Building paths with pathlib
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)
Inspecting a Path object

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)
Writing, reading, and checking existence
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']
Listing files with glob

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'))
Older style with os.path and glob module

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)
json.dump and json.load for files

Your turn

0 of 3 solved

Exercise 1

+40 XP
Use pathlib. Build note = Path('notes') / 'day1.txt', then store its .name, .stem and .suffix in name, stem and suffix. Create the notes folder with mkdir(parents=True, exist_ok=True), write 'Set out at dawn.' to the file with write_text(), and read it back into text with read_text().
from pathlib import Path


note = None  # Path('notes') joined with 'day1.txt'

Run your code to check it against the tests.

Exercise 2

+40 XP
Create the folder logs, then write each file named in FILES into that folder with some text (anything will do). Then replace the [] in text_files = [] with the sorted names of the files in logs that end in .txt, found with Path('logs').glob('*.txt'). glob can return the names in any order, so sort them.
from pathlib import Path


FILES = ['b.txt', 'a.txt', 'c.log', 'd.txt']


# make logs, write the files, then find the .txt ones
text_files = []

Run your code to check it against the tests.

Exercise 3

+40 XP
Write save_settings(path, data), which writes the dictionary data to the file at path with json.dump(data, f, indent=2), and load_settings(path), which reads it back with json.load, or returns {} if the file does not exist. indent=2 spreads the JSON over several lines, with each key pushed in by two spaces.
import json
from pathlib import Path




def save_settings(path, data):
    pass




def load_settings(path):
    # {} when the file is missing
    pass

Run your code to check it against the tests.