Use PurePosixPath to inspect an archive member

Use PurePosixPath to inspect an archive member

Archive formats commonly describe members with forward-slash-separated names, regardless of the host operating system. PurePosixPath is a useful fit for inspecting such a name because it applies POSIX path rules without accessing the filesystem. This example receives package-1.0/docs/guide.txt, treats package-1.0 as the expected archive root, and prints the member path below that root.

is_relative_to() checks that the parsed member is lexically below the declared root. The second assertion exposes the exact three components, while the third reads the final suffix. The output, docs/guide.txt, is calculated by relative_to() and contains no platform-dependent separator.

These checks are lexical, not archive validation. In particular, PurePosixPath does not open an archive, prove that the member exists, normalize a .. component, or protect a later extraction operation. An extraction routine still needs its own containment policy and must account for its archive library's handling of links and special entries. PurePosixPath arrived with pathlib in Python 3.4; this particular example requires Python 3.9 because is_relative_to() was introduced then. The official pathlib reference documents pure paths, parts, suffixes, and the lexical limitation of is_relative_to().

AI assistance disclosure: This article was drafted with AI assistance and should be reviewed in the context of its application.

from pathlib import PurePosixPath

member = PurePosixPath("package-1.0/docs/guide.txt")
root = PurePosixPath("package-1.0")

assert member.is_relative_to(root)
assert member.parts == ("package-1.0", "docs", "guide.txt")
assert member.suffix == ".txt"

print(member.relative_to(root).as_posix())
docs/guide.txt

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic