liveBook · Manning

Current working directory

As explained in The Quick Python Book, Fourth Edition

The current working directory is the process's filesystem directory used as the default reference point for resolving relative paths.

The current working directory is the directory where a running Python program considers itself to be. It supplies the anchor for relative paths and may differ from the directory containing the program itself. section 12.2.1 section 12.2.2

Use these operations to inspect and work from the current directory:

  • `os.getcwd()` returns the current working directory as an absolute path. section 12.2.2
  • `os.curdir` supplies the portable current-directory indicator, conventionally represented by `.`. section 12.2.2
  • `os.listdir(os.curdir)` lists files and folders in the current working directory. section 12.2.6
  • `os.chdir(path)` changes the process's current working directory; later relative paths use the new location. section 12.2.2

Inspect, list, and change location

```python import os print(os.getcwd()) print(os.listdir(os.curdir)) os.chdir('sample_data') print(os.getcwd()) ``` After `os.chdir('sample_data')`, listing with `os.curdir` refers to `sample_data`, not the former directory. section 12.2.2

Relative paths can also gain context by appending them to an existing absolute path. With `pathlib`, `pathlib.Path().cwd()` retrieves the current location, but pathlib does not change the process-wide working directory; create another path object instead. section 12.2.1 section 12.2.3

import os
os.getcwd()
 
'/content'

A minimal interactive session shows `os.getcwd()` returning the process's current location. section 12.2.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines the directory context and demonstrates inspection, listing, and changing it, without descending into operating-system internals.
Examples
Demonstrates `os.getcwd()`, `os.listdir(os.curdir)`, `os.chdir('sample_data')`, and `pathlib.Path().cwd()`.
What it assumes
Assumes general Python and filesystem familiarity while introducing relative-path anchoring and process directory state.
What you can do after
Operate filesystem context with `os.getcwd`, `os.curdir`, `os.listdir`, `os.chdir`, and `pathlib`.
How it connects
Connects relative paths, absolute paths, `os.listdir`, `os.getcwd`, `os.chdir`, and `pathlib`.

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.