Skip to content

Working with File Paths

DivvyCr edited this page Apr 28, 2020 · 1 revision

Often you will want to fetch files from specific locations, or store data to files in a specific directory. This section aims to provide some basic information to use Python's os.path module.

For official, extensive documentation, see docs.python.org.

Format

Python's path module attempts to adapt all paths to your operating system's format (i.e. consistenly use either \ or / as separators, which can be found by using os.sep), but it sometimes mixes the separators, so you might end up with some paths such as ~/path/to/file\path/to. At the same time, it doesn't seem to cause any problems.

Paths can be simple strings representing your standard OS paths - you may use the forward slash separator even if your OS uses the backslash (e.g. "C:/Users/ballchaser" or "C:\\Users\\ballchaser" on Windows). Path-like objects can be explored here.

Referencing the Working Directory

__file__ is a special variable that contains the path to the current module/file. Therefore, you can use os.path.dirname(__file__) to get the path to the working directory.

Joining Paths

To extend a path, you can use the os.path.join(path, *paths) method, where the path is the current path (usually the working directory, or the home directory), and *paths are relative paths to join to path.

The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last. Note that it can lead to a file.

Checks

os.path.exists(path) - Returns true if the given path refers to an existing path.

os.path.isfile(path) - Returns true if the given path is an existing regular file.

os.path.isdir(path) - Returns true if the given path is an existing directory.