Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. pathlib.Path()

pathlib.Path()

The pathlib module provides a modern API for working with file paths as objects. It produces more intuitive and readable code than the string-based os.path approach.

Syntax

from pathlib import Path

# Create a Path object.
p = Path('file path')

# Read an entire text file at once.
content = p.read_text(encoding='utf-8')

# Write text to a file all at once.
p.write_text('content', encoding='utf-8')

# Get files matching a pattern.
file_list = p.glob('**/*.txt')

# Create a directory.
p.mkdir(parents=True, exist_ok=True)

# Delete a file.
p.unlink()

Main Attributes and Methods

Attribute / MethodDescription
Path(path)Creates a path object. Automatically handles the path separator for the current OS.
p.read_text(encoding='utf-8')Reads the entire contents of a file as a string.
p.write_text(text, encoding='utf-8')Writes a string to a file. Creates the file if it does not exist.
p.glob(pattern)Returns files matching the pattern as a generator. Use ** to search recursively.
p.mkdir(parents=False, exist_ok=False)Creates a directory. Set parents=True to create all missing parent directories at once.
p.unlink()Deletes a file. Cannot be used on directories.
p.suffixReturns the file extension (e.g., .txt).
p.stemReturns the filename without its extension.
p.nameReturns the final component of the path (the filename).
p.parentReturns the path of the parent directory.
p.exists()Returns True if the path exists.
p / 'child path'Joins paths using the / operator.

Sample Code

from pathlib import Path

# Create a Path object and retrieve information about it.
p = Path('/Users/user/documents/report.txt')
print(p.name)    # Outputs 'report.txt'.
print(p.stem)    # Outputs 'report'.
print(p.suffix)  # Outputs '.txt'.
print(p.parent)  # Outputs '/Users/user/documents'.

# Join paths with the / operator (equivalent to os.path.join).
base = Path('/var/www')
full = base / 'html' / 'index.php'
print(full)  # Outputs '/var/www/html/index.php'.

# Read from and write to a text file.
config_path = Path('config.txt')
config_path.write_text('key=value\n', encoding='utf-8')
content = config_path.read_text(encoding='utf-8')
print(content)  # Outputs 'key=value'.

# Create a directory.
output_dir = Path('output/reports/2025')
output_dir.mkdir(parents=True, exist_ok=True)

# Use glob() to find files matching a pattern.
src_dir = Path('.')
for py_file in src_dir.glob('**/*.py'):  # Recursively search for Python files.
    print(py_file)

# Check whether a path exists with exists().
p2 = Path('config.txt')
if p2.exists():
    text = p2.read_text(encoding='utf-8')
    p2.unlink()  # Delete the file.

# Get the current working directory.
cwd = Path.cwd()
print(f'Current directory: {cwd}')

# Get the directory containing the current script.
script_dir = Path(__file__).parent
print(f'Script location: {script_dir}')

Notes

pathlib.Path treats paths as objects rather than plain strings, so you can access each part of a path through attributes and join paths with the / operator for more intuitive code. Since Python 3.6, most of the standard library accepts Path objects directly, so you no longer need to convert them to strings with str(p).

read_text() and write_text() open and close the file automatically, so you do not need to write a with open(...) block. When working with binary files, use read_bytes() and write_bytes() instead, and be careful not to mix them up with the text-mode methods.

For the basics of reading and writing files, see open() / file.read() / file.write().

If you find any errors or copyright issues, please .