Python Glossary Русский

all Python 3osfunction

os.path.dirname

os.path — path parsing

Return the path without its final component (the parent directory).

Syntax

os.path.dirname(path)

For a bare file name it returns an empty string, not '.': dirname('file.txt') gives ''. Passing that result to os.listdir or os.makedirs is a common bug; use dirname(p) or '.'. A trailing slash makes the path a directory: dirname('a/b/') returns 'a/b'. The function never touches the filesystem.

Examples

import os
print(os.path.dirname('/a/b/c.txt'))   # → /a/b
path = '/home/user/file.txt'
print(os.path.dirname(path))  # → /home/user
print(repr(os.path.dirname('file.txt')))  # → '' — каталога в пути нет

See also

Open in the full glossarydocs.python.orgReport an inaccuracy