liveBook · Manning

Os.path.splitext

As explained in The Quick Python Book, Fourth Edition

os.path.splitext is a Python function that separates a pathname into its root portion and final dotted extension.

Use os.path.splitext(path) to separate a pathname from its final dotted extension. It returns a two-element tuple: the pathname without the extension, then the extension including its dot. If there is no dotted extension, the second element is an empty string. section 12.2.4 section 12.6.2

os.path.splitext(os.path.join('some', 'directory', 'path.jpg'))
 
('some/directory/path', '.jpg')

The directory stays in the first element: splitting some/directory/path.jpg gives ('some/directory/path', '.jpg'). section 12.2.4

For a file filter, compare os.path.splitext(file)[1] with '.test'. A filesystem walk can then skip symlinks and add the sizes of matching files. Unlike os.path.split, which separates the final name from its directory, splitext separates the extension from the rest of the pathname. Dotted extensions are a naming convention, not a universal indication of file type. section 12.2.4 section 12.6.2

# txt_file_size.py

import os

size = 0
for root, dirs, files in os.walk(os.curdir):
   for file in files:
       file_path = os.path.join(root, file)
       if (not os.path.islink(file_path) 
           and os.path.splitext(file)[1] == '.test'):
           size += os.path.getsize(file_path)

print(f"Total size of all  files that are not symlinks: {size} bytes")

A complete script uses tuple index 1 to select .test files while totaling the sizes of files that are not symlinks. section 12.6.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines both tuple elements and demonstrates extension checks, without detailing parsing internals.
Examples
Shows a path.jpg split into pathname and .jpg, plus scripts selecting .test files during recursive traversal.
What it assumes
Assumes familiarity with Python imports, tuple indexing, and filesystem loops rather than teaching them from zero.
What you can do after
Apply it via os.path to test a file's extension before totaling its size or moving it.
How it connects
Connects pathname manipulation to os.path.split, os.path.join, os.walk, and pathlib.Path.suffix.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.