Absolute and Relative File Paths

An absolute path identifies a location from a filesystem root. A relative path needs a base directory supplied by the process or caller.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace two working directories
  2. Choose where the base comes from
  3. Resolve the same relative name from two working directories
  4. Record the resolved location when reporting errors

Trace two working directories

Resolving data/report.csv from a project directory opens that project's data file. Resolving it from the user's home directory names a different location. A running process has environmental state such as the current working directory.

Choose where the base comes from

A user-provided command path can be relative to the caller's directory. A resource bundled with a module may instead be located relative to the installed package. Record the base when reproducing a run.[1]

Resolve the same relative name from two working directories

A program reading data/input.txt from a project root sees the file under that root. Running it from the project's tools directory normally resolves that name under tools/data instead. If the program expects a directory relative to its configuration file, use that file's directory explicitly. See joining path components.

Working directory /project → /project/data/input.txt
Working directory /project/tools → /project/tools/data/input.txt
An explicit base can make resolution independent of process startup location

Record the resolved location when reporting errors

Moving a script does not necessarily move the process working directory. Test starting the same program from an unrelated directory. Use platform-aware path handling when paths can include a drive, root or distinct separator.

References

  1. Python Software Foundation, io: Core Tools for Working with Streams ↩