add File.glob and Path.stem
This commit is contained in:
parent
d5702a4ba1
commit
c9571dd7e2
39
blib/path.py
39
blib/path.py
|
@ -4,7 +4,11 @@ import os
|
|||
import shutil
|
||||
import sys
|
||||
|
||||
from collections.abc import Iterator, Sequence
|
||||
from glob import iglob
|
||||
|
||||
from .enums import FileType, XdgDir
|
||||
from .errors import FileError
|
||||
from .misc import FileSize
|
||||
|
||||
try:
|
||||
|
@ -69,6 +73,11 @@ class Path(str):
|
|||
return self.__class__(os.path.dirname(self))
|
||||
|
||||
|
||||
@property
|
||||
def stem(self) -> str:
|
||||
return self.name.rstrip(self.ext).rstrip(".")
|
||||
|
||||
|
||||
def join(self, *parts: str, normalize: bool = False) -> Self: # type: ignore[override]
|
||||
"""
|
||||
Append a path segment
|
||||
|
@ -208,6 +217,36 @@ class File(Path):
|
|||
return tuple(types)
|
||||
|
||||
|
||||
def glob(self,
|
||||
pattern: str = "**",
|
||||
recursive: bool = False,
|
||||
hidden: bool = False,
|
||||
ext: Sequence[str] | None = None) -> Iterator[File]:
|
||||
"""
|
||||
Iterate through a directory with paths matching a specific pattern
|
||||
|
||||
.. note:: See :class:`glob.iglob` for pattern usage
|
||||
|
||||
:param pattern: Filename pattern to match
|
||||
:param recursive: Whether or not to search through sub-directories
|
||||
:param hidden: List hidden files
|
||||
:param ext: Include only the specified extensions in the result if set
|
||||
:raises FileError: If the path is not a directory or does not exist
|
||||
"""
|
||||
|
||||
if self.isfile:
|
||||
raise FileError.IsFile(self)
|
||||
|
||||
if not self.exists:
|
||||
raise FileError.NotFound(self)
|
||||
|
||||
for path in iglob(pattern, root_dir = self, recursive = recursive, include_hidden = hidden):
|
||||
filepath = self.join(path)
|
||||
|
||||
if ext is None or filepath.ext in ext:
|
||||
yield filepath
|
||||
|
||||
|
||||
def mkdir(self, mode: int = 0o755) -> None:
|
||||
"""
|
||||
Create a directory and all parent directories
|
||||
|
|
Loading…
Reference in a new issue