Replacing path manipulation from string concatenation with Python pathlib: A practical look at name, suffix, and parent

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About this article
This article was generated using an AI-assisted automated workflow. We check the official Python documentation and see what changes when you use pathlib.Path instead of constructing paths as strings, through a safe experiment using only temporary files.

Verification status: Verified execution on Python 3.13.5
Information verification baseline date: October 5, 2026

When handling files in Python, paths are sometimes built using string concatenation like "folder/" + name While this works for short code, path separators differ between Windows and Linux, and string processing increases every time you extract a parent directory or extension.

pathlib.PathUsing

allows you to treat paths not as strings, but as objects that can be manipulated as paths.

Trying it out in a temporary directorydata/report.csvThe following code does not touch existing files, but instead creates

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory(prefix="papanda-pathlib-") as temp_dir:
    base = Path(temp_dir)
    data_dir = base / "data"
    data_dir.mkdir()

    report = data_dir / "report.csv"
    report.write_text("name,value\nA,1\n", encoding="utf-8")

    print("name   =", report.name)
    print("suffix =", report.suffix)
    print("parent =", report.parent.name)
    print("exists =", report.exists())
    print("resolve=", report.resolve())

inside a temporary directory for observation.

  • nameThis was executed in this environment using Python 3.13.5, and the following was verified.report.csv

  • suffix is .csv

  • parent.name is data

  • exists() is True

  • resolve() returns the absolute path

Differences from string concatenation

For example, consider the following code.

folder = "data"
filename = "report.csv"
path = folder + "/" + filename

This code is simple, but"/" includes it manually.

Path, you can write it as follows.

from pathlib import Path

path = Path("data") / "report.csv"

/ is not division, but ratherPath is used to concatenate paths between objects or strings.

The official Python documentation also states that when using pathlib for the first time, normally Path is recommended.

Using Path makes operations self-explanatory

flowchart LR
    A["Path('data')"] --> B["/ 'report.csv'"]
    B --> C["Pathオブジェクト"]
    C --> D["name"]
    C --> E["suffix"]
    C --> F["parent"]
    C --> G["exists()"]
    C --> H["resolve()"]

Rather than slicing and concatenating strings, intents such as "I want to know the file name," "I want to know the parent," and "I want to check for existence" are directly expressed in the code.

Comparing name, suffix, and parent

Path("data/report.csv") Taking as an example,

OperationMeaningExample
.nameFinal file namereport.csv
.suffixFinal extension.csv
.parentParent pathdata
.exists()Whether it actually existsTrue/False
.resolve()Absolute Path Conversion and ResolutionEnvironment-dependent

Especially exists() and resolve() are operations related to the actual file system.

On the other hand, PurePath the family is intended for path calculations that do not involve I/O. The official Python documentation also explains pure paths and concrete paths separately.

resolve() is not a mere string conversion

resolve() not only converts relative paths to absolute paths, but also resolves symbolic links and .. also organizes elements such as .

from pathlib import Path

p = Path("docs/../sample.txt")
print(p.resolve())

However, the actual path it resolves to depends on the execution environment.

Also, resolve(strict=True) setting it to may result in OSError occurring for non-existent paths. In processes where you want to handle paths strictly, including existence checks, strict also keep the meaning of in mind.

Try changing just one location

In the first sample,

report = data_dir / "report.csv"

to

report = data_dir / "archive.tar.gz"

let's change it to.

.suffix is only the final extension, so

.gz

is formed.

If you want to view multiple extensions together, use .suffixes.

print(report.suffixes)

In this way, it can be handled as a Path feature rather than a simple string suffix search.

Path notation differs between Windows and Linux

Path notation differs, such as C:\Users\... on Windows and /home/... on Linux.

PathSince creates a concrete path corresponding to the running OS, there is less need to hardcode delimiters yourself in standard file operations.

However, when you only want to analyze a Windows path structure on Linux, pure paths such as PureWindowsPath are suitable.

exists() alone does not guarantee processing safety

exists()Even if True is true, another process might delete the file immediately afterward.

Therefore, it

if path.exists():

    # 絶対安全

is not considered.

Exception handling is also required when actually opening the file.

from pathlib import Path

path = Path("sample.txt")

try:
    text = path.read_text(encoding="utf-8")
except FileNotFoundError:
    print("ファイルが見つかりません")

exists() is useful for checking status, but it does not guarantee that subsequent processing will always succeed.

When to replace with Path

This is especially effective in code like the following.

  • Concatenating folder names and file names repeatedly

  • Extracting extensions or parent folders

  • Handling relative and absolute paths

  • Wanting to run on both Windows and Linux

  • Searching for files using glob

  • Wanting to handle everything consistently up to reading and writing files

On the other hand, URLs passed to external APIs are not filesystem paths. Avoid constructing URLs with Path and use mechanisms designed for URLs instead.

Daily-Code-Samples

In the complete version, a temporary directory is automatically created, the results are inspected, and [SUCCESS] / [FAILED] is displayed.

Official Documentation

Document information

Article title
Replacing path manipulation from string concatenation with Python pathlib: A practical look at name, suffix, and parent
Published
Updated
Source
https://papanda925.com/?p=17990&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL