Legends ofPythos
Claim your name
The Standard Library

Files and folders

Lesson 2 of 7

Watch the lesson1:29 ยท 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

# Joining parts is as simple as using the / operator
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.
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)
Inspecting a Path object

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

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

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)
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 it with some text (anything will do). Then store in text_files the sorted names of the files in logs that end in .txt, found with Path('logs').glob('*.txt'). The order glob returns is not guaranteed, so sort the names.
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.
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.