CodeBlanks Logo Icon CodeBlanks

Path

Learn path objects with Path().

The Path object

Python's pathlib module represents file paths as objects. You import the Path class with from pathlib import Path. The call Path("notes.txt") returns a path object you can operate on.

The old approach used string functions like os.path.join; pathlib instead keeps the path as an object and offers operations as methods. You get the name with .name and the suffix with .suffix. This is safer than splitting strings.

The stem and parent attributes

A Path object has many useful attributes. .name gives the filename with extension, .stem the name without extension, .suffix the extension. .parent returns the parent folder as a Path.

For example Path("docs/report.pdf").stem returns "report". These attributes are safer than using string methods to extract parts; they parse the path form correctly.

Practice Print the name and suffix of a Path

Start with from pathlib import Path. Create a path object with p = Path("report.pdf"). Print the name with print(p.name) and the suffix with print(p.suffix).

Starter code

main.py
# Import the Path class
# Create the p path object
# Print name and suffix

Sample solution

main.py
# Import the Path class
from pathlib import Path
# Create the p path object
p = Path("report.pdf")
# Print name and suffix
print(p.name)
print(p.suffix)

Expected output

report.pdf
.pdf

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does Path("report.pdf").suffix return?

  • ".pdf" Correct answer
  • "report"
  • "report.pdf"
  • "pdf"

Explanation: The suffix attribute gives the extension with the dot.

2 Import the Path class

Question
from pathlib import ____

p = Path("notes.txt")
print(p.name)
Answer
from pathlib import Path

p = Path("notes.txt")
print(p.name)

Explanation: The Path class is imported from pathlib.

3 Match the Path attributes

Term Meaning
.name Filename
.stem Name without extension
.suffix Extension
.parent Parent folder

All lessons in Intermediate