liveBook · Manning

Os.listdir

As explained in The Quick Python Book, Fourth Edition

os.listdir is a Python standard-library function that returns the names of entries in a filesystem directory.

os.listdir returns a list of filenames and folder names inside a directory. With a relative path, Python resolves that path from the current working directory. section 12.2.2 section 12.2.1

Use os.listdir with these practical rules:

  • Pass os.curdir to list the current working directory portably instead of writing a literal dot. section 12.2.2 section 12.2.6
  • The result contains directory entries but does not include the os.curdir or os.pardir indicators. section 12.4
  • After os.chdir changes the working directory, the same relative listing refers to the new location. section 12.2.2
  • Use glob when you need shell-style wildcard filtering such as *.json, ?.tmp, or [0-9].tmp. section 12.4

List the current directory

import os os.listdir(os.curdir) # ['.config', 'sample_data'] os.chdir('sample_data') os.listdir(os.curdir) # ['anscombe.json', 'README.md', 'california_housing_train.csv', ...] section 12.2.2

os.chdir('/content/sample_data')
os.listdir(os.curdir)
 
['anscombe.json',
 'README.md',
 'california_housing_train.csv',
 'california_housing_test.csv',
 'mnist_test.csv',
 'mnist_train_small.csv']

Inspect a concrete listing of files in a changed working directory. section 12.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines returned entries, relative-path resolution, and current-directory effects, but defers deeper filesystem implementation details.
Examples
Demonstrates listings before and after os.chdir, including Colaboratory's sample_data directory and wildcard alternatives with glob.
What it assumes
Assumes familiarity with filesystem paths while teaching current working directories, relative paths, and os.curdir usage.
What you can do after
Apply it via Python's os module to inspect directory contents relative to an explicit path or current working directory.
How it connects
Connects os.listdir with current working directories, relative paths, os.curdir, os.chdir, glob, and pathlib.

Also explained in

Compare how 3 books explain os.listdir →

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.