October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

Convert a String to a Path in Python: pathlib, os.fspath, and Safe Joining

Use pathlib.Path(string) for the usual way to convert a Python string into a platform-aware path object. Learn when to use str(), os.fspath(), pure paths, or os.path—and why constructing a path does not check that it exists.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use pathlib.Path to turn a string into a path object: Path("some/folder/file.txt"). It is the standard choice for paths used with the local filesystem, and Python selects the appropriate concrete path type for the operating system running your code. Python’s pathlib documentation recommends Path for the usual case.

Convert a string to a path with pathlib

Import Path from pathlib, then pass the path string to its constructor:

As an Amazon Associate I earn from qualifying purchases.

from pathlib import Path

path = Path("some/folder/file.txt")

The result is a Path object, not a plain string. You can use it with path-aware APIs and methods, for example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from pathlib import Path

path = Path("data") / "input.csv"
print(path.name)  # input.csv

Python’s pathlib documentation says, “If you’ve never used this module before or just aren’t sure which class is right for you, Path is most likely what you need.”

When you need a string instead of a Path object

Most APIs that accept filesystem paths can accept a Path directly through Python’s os.PathLike protocol. If an API specifically requires a string, use str(path). To obtain the filesystem representation through the path protocol, use os.fspath(path):

import os
from pathlib import Path

path = Path("some/folder/file.txt")
plain_string = str(path)
filesystem_string = os.fspath(path)

The string representation uses the platform’s native path form, including its separators. See the pathlib documentation for details.

Choose the right path class

  • Path: Use for ordinary local-filesystem paths. It selects the concrete path class for the current platform and provides filesystem I/O operations.
  • PurePath: Use when you need path operations without filesystem I/O; it uses the path flavor of the current system.
  • PureWindowsPath or PurePosixPath: Use to manipulate Windows or POSIX path syntax regardless of the operating system running your code. Pure paths do not access the filesystem. A concrete WindowsPath cannot be instantiated on a non-Windows system.
  • os.path: Use for string-oriented, lower-level operations or when continuing an existing codebase’s style. Its functions accept strings, bytes, and os.PathLike objects; the default implementation follows the host platform.

For the documented behavior of path flavors, see pathlib; for os.path inputs and platform selection, see os.path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Join path segments without assuming the result stays under a base

With pathlib, append a segment using the / operator or joinpath():

from pathlib import Path

base = Path("data")
file_path = base / "input.csv"

A later absolute segment can replace the earlier path instead of being appended. Windows rooted-relative segments also have drive-specific behavior. If a segment comes from external or otherwise unexpected input, joining alone does not guarantee that the final path remains beneath a trusted directory. Check the resulting path against your application’s security and containment requirements. The pathlib documentation describes these joining rules.

Creating a Path does not check whether a file exists

Path("some/folder/file.txt") constructs a path object; it does not establish that a file or directory with that name exists. If existence matters, check it explicitly:

if path.exists():
    print("The path exists")

Use resolve() only when you intend to resolve or canonicalize the path. Resolution can depend on filesystem state and platform-specific link behavior. See the pathlib reference for the method’s behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use os.path when string-oriented functions fit your code

os.path is a valid alternative to pathlib, particularly in code that already uses its functions. It provides operations on path values rather than methods on path objects, and its default behavior is selected for the host operating system. The Python os.path documentation covers accepted path-like inputs and available functions. For new, ordinary filesystem paths, Path is the simpler default.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.