pathier

 1import argparse
 2
 3import griddle
 4import noiftimer
 5import printbuddies
 6import younotyou
 7
 8from .pathier import Pathier, Pathish, Pathy
 9
10__all__ = ["Pathier", "Pathy", "Pathish"]
11
12
13@noiftimer.time_it()
14def sizeup():
15    """Print the sub-directories and their sizes of the current working directory."""
16    parser = argparse.ArgumentParser("sizeup")
17    parser.add_argument(
18        "-i",
19        "--ignore",
20        nargs="*",
21        default=[],
22        type=str,
23        help="Directory patterns to ignore.",
24    )
25    args = parser.parse_args()
26    matcher = younotyou.Matcher(exclude_patterns=args.ignore)
27    sizes: dict[str, int] = {}
28    folders = [
29        folder
30        for folder in Pathier.cwd().iterdir()
31        if folder.is_dir() and str(folder) in matcher
32    ]
33    print(f"Sizing up {len(folders)} directories...")
34    for folder in printbuddies.track(folders, "Scanning directories"):
35        try:
36            sizes[folder.name] = folder.size
37        except Exception as e:
38            pass
39    total_size = sum(sizes[folder] for folder in sizes)
40    size_list = [
41        (folder, Pathier.format_bytes(sizes[folder]))
42        for folder in sorted(list(sizes.keys()), key=lambda f: sizes[f], reverse=True)
43    ]
44    print(griddle.griddy(size_list, ["Dir", "Size"]))
45    print(f"Total size of '{Pathier.cwd()}': {Pathier.format_bytes(total_size)}")
46
47
48__version__ = "1.5.4"
class Pathier(pathlib.Path):
 17class Pathier(pathlib.Path):
 18    """Subclasses the standard library pathlib.Path class."""
 19
 20    def __new__(
 21        cls,
 22        *args: Self | str | pathlib.Path,
 23        **kwargs: Any,
 24    ) -> Self:
 25        if cls is Pathier:
 26            cls = WindowsPath if os.name == "nt" else PosixPath
 27        self = cls._from_parts(args)  # type: ignore
 28        if not self._flavour.is_supported:  # type: ignore
 29            raise NotImplementedError(
 30                "cannot instantiate %r on your system" % (cls.__name__,)
 31            )
 32        if "convert_backslashes" in kwargs:
 33            self.convert_backslashes = kwargs["convert_backslashes"]
 34        else:
 35            self.convert_backslashes = True
 36        return self  # type: ignore
 37
 38    @property
 39    def convert_backslashes(self) -> bool:
 40        """If True, when `self.__str__()`/`str(self)` is called, string representations will have double backslashes converted to a forward slash.
 41
 42        Only affects Windows paths."""
 43        try:
 44            return self._convert_backslashes
 45        except Exception as e:
 46            return True
 47
 48    @convert_backslashes.setter
 49    def convert_backslashes(self, should_convert: bool):
 50        self._convert_backslashes = should_convert
 51
 52    def __str__(self) -> str:
 53        path = super().__new__(pathlib.Path, self).__str__()  # type: ignore
 54        if self.convert_backslashes:
 55            path = path.replace("\\", "/")
 56        return path
 57
 58    # ===============================================stats===============================================
 59    @property
 60    def dob(self) -> datetime.datetime | None:
 61        """Returns the creation date of this file or directory as a `dateime.datetime` object."""
 62        return (
 63            datetime.datetime.fromtimestamp(self.stat().st_ctime)
 64            if self.exists()
 65            else None
 66        )
 67
 68    @property
 69    def age(self) -> float | None:
 70        """Returns the age in seconds of this file or directory."""
 71        return (
 72            (datetime.datetime.now() - self.dob).total_seconds() if self.dob else None
 73        )
 74
 75    @property
 76    def mod_date(self) -> datetime.datetime | None:
 77        """Returns the modification date of this file or directory as a `datetime.datetime` object."""
 78        return (
 79            datetime.datetime.fromtimestamp(self.stat().st_mtime)
 80            if self.exists()
 81            else None
 82        )
 83
 84    @property
 85    def mod_delta(self) -> float | None:
 86        """Returns how long ago in seconds this file or directory was modified."""
 87        return (
 88            (datetime.datetime.now() - self.mod_date).total_seconds()
 89            if self.mod_date
 90            else None
 91        )
 92
 93    @property
 94    def last_read_time(self) -> datetime.datetime | None:
 95        """Returns the last time this object made a call to `self.read_text()`, `self.read_bytes()`, or `self.open(mode="r"|"rb")`.
 96        Returns `None` if the file hasn't been read from.
 97
 98        Note: This property is only relative to the lifetime of this `Pathier` instance, not the file itself.
 99        i.e. This property will reset if you create a new `Pathier` object pointing to the same file.
100        """
101        return (
102            datetime.datetime.fromtimestamp(self._last_read_time)
103            if self._last_read_time
104            else None
105        )
106
107    @property
108    def modified_since_last_read(self) -> bool:
109        """Returns `True` if this file hasn't been read from or has been modified since the last time this object
110        made a call to `self.read_text()`, `self.read_bytes()`, or `self.open(mode="r"|"rb")`.
111
112        Note: This property is only relative to the lifetime of this `Pathier` instance, not the file itself.
113        i.e. This property will reset if you create a new `Pathier` object pointing to the same file.
114
115        #### Caveat:
116        May not be accurate if the file was modified within a couple of seconds of checking this property.
117        (For instance, on my machine `self.mod_date` is consistently 1-1.5s in the future from when `self.write_text()` was called according to `time.time()`.)
118        """
119        return (
120            False
121            if not self.mod_date
122            or not self.last_read_time
123            or self.mod_date < self.last_read_time
124            else True
125        )
126
127    @property
128    def size(self) -> int:
129        """Returns the size in bytes of this file or directory.
130
131        If this path doesn't exist, `0` will be returned."""
132        if not self.exists():
133            return 0
134        elif self.is_file():
135            return self.stat().st_size
136        elif self.is_dir():
137            return sum(file.stat().st_size for file in self.rglob("*.*"))
138        return 0
139
140    @property
141    def formatted_size(self) -> str:
142        """The size of this file or directory formatted with `self.format_bytes()`."""
143        return self.format_bytes(self.size)
144
145    @staticmethod
146    def format_bytes(size: int) -> str:
147        """Format `size` with common file size abbreviations and rounded to two decimal places.
148        >>> 1234 -> "1.23 kb" """
149        unit = "bytes"
150        for unit in ["bytes", "kb", "mb", "gb", "tb", "pb"]:
151            if unit != "bytes":
152                size *= 0.001  # type: ignore
153            if size < 1000 or unit == "pb":
154                break
155        return f"{round(size, 2)} {unit}"
156
157    def is_larger(self, path: Self) -> bool:
158        """Returns whether this file or folder is larger than the one pointed to by `path`."""
159        return self.size > path.size
160
161    def is_older(self, path: Self) -> bool | None:
162        """Returns whether this file or folder is older than the one pointed to by `path`.
163
164        Returns `None` if one or both paths don't exist."""
165        return self.dob < path.dob if self.dob and path.dob else None
166
167    def modified_more_recently(self, path: Self) -> bool | None:
168        """Returns whether this file or folder was modified more recently than the one pointed to by `path`.
169
170        Returns `None` if one or both paths don't exist."""
171        return (
172            self.mod_date > path.mod_date if self.mod_date and path.mod_date else None
173        )
174
175    # ===============================================navigation===============================================
176    def mkcwd(self):
177        """Make this path your current working directory."""
178        os.chdir(self)
179
180    @property
181    def in_PATH(self) -> bool:
182        """Return `True` if this path is in `sys.path`."""
183        return str(self) in sys.path
184
185    def add_to_PATH(self, index: int = 0):
186        """Insert this path into `sys.path` if it isn't already there.
187
188        #### :params:
189
190        `index`: The index of `sys.path` to insert this path at."""
191        path = str(self)
192        if not self.in_PATH:
193            sys.path.insert(index, path)
194
195    def append_to_PATH(self):
196        """Append this path to `sys.path` if it isn't already there."""
197        path = str(self)
198        if not self.in_PATH:
199            sys.path.append(path)
200
201    def remove_from_PATH(self):
202        """Remove this path from `sys.path` if it's in `sys.path`."""
203        if self.in_PATH:
204            sys.path.remove(str(self))
205
206    def _get_path_part_rindex(self, name: str) -> int | None:
207        """Returns the index value for the last occurrence of `name` if it is in this path instance."""
208        if name not in self.parts:
209            raise Exception(f"{name} is not a parent of {self}")
210        lastdex = len(self.parts) - 1
211        rev_parts = self.parts[::-1]
212        return lastdex - rev_parts.index(name)
213
214    def moveup(self, name: str) -> Self:
215        """Return a new `Pathier` object that is a parent of this instance.
216
217        `name` is case-sensitive and raises an exception if it isn't in `self.parts`.
218        >>> p = Pathier("C:/some/directory/in/your/system")
219        >>> print(p.moveup("directory"))
220        >>> "C:/some/directory"
221        >>> print(p.moveup("yeet"))
222        >>> "Exception: yeet is not a parent of C:/some/directory/in/your/system" """
223        index = self._get_path_part_rindex(name)
224        if index is None:
225            raise Exception(f"{name} is not a parent of {self}")
226        return self - (len(self.parts) - index - 1)
227        return self.__class__(*(self.parts[: index + 1]))
228
229    def __sub__(self, levels: int) -> Self:
230        """Return a new `Pathier` object moved up `levels` number of parents from the current path.
231        >>> p = Pathier("C:/some/directory/in/your/system")
232        >>> new_p = p - 3
233        >>> print(new_p)
234        >>> "C:/some/directory" """
235        path = self
236        for _ in range(levels):
237            path = path.parent
238        return path
239
240    def move_under(self, name: str) -> Self:
241        """Return a new `Pathier` object such that the stem is one level below the given folder `name`.
242
243        `name` is case-sensitive and raises an exception if it isn't in `self.parts`.
244        >>> p = Pathier("a/b/c/d/e/f/g")
245        >>> print(p.move_under("c"))
246        >>> 'a/b/c/d'"""
247        index = self._get_path_part_rindex(name)
248        if index is None:
249            raise Exception(f"{name} is not a parent of {self}")
250        return self - (len(self.parts) - index - 2)
251
252    def separate(self, name: str, keep_name: bool = False) -> Self:
253        """Return a new `Pathier` object that is the relative child path after `name`.
254
255        `name` is case-sensitive and raises an exception if it isn't in `self.parts`.
256
257        #### :params:
258
259        `keep_name`: If `True`, the returned path will start with `name`.
260        >>> p = Pathier("a/b/c/d/e/f/g")
261        >>> print(p.separate("c"))
262        >>> 'd/e/f/g'
263        >>> print(p.separate("c", True))
264        >>> 'c/d/e/f/g'"""
265        if name not in self.parts:
266            raise Exception(f"{name} is not a parent of {self}")
267        if keep_name:
268            return self.__class__(*self.parts[self.parts.index(name) :])
269        return self.__class__(*self.parts[self.parts.index(name) + 1 :])
270
271    # ============================================write and read============================================
272    def mkdir(self, mode: int = 511, parents: bool = True, exist_ok: bool = True):
273        """Create this directory.
274
275        Same as `Path().mkdir()` except `parents` and `exist_ok` default to `True` instead of `False`.
276        """
277        super().mkdir(mode, parents, exist_ok)
278
279    def touch(self, mode: int = 438, exist_ok: bool = True):
280        """Create file (and parents if necessary)."""
281        self.parent.mkdir()
282        super().touch(mode, exist_ok)
283
284    def open(  # type: ignore
285        self,
286        mode: str = "r",
287        buffering: int = -1,
288        encoding: str | None = None,
289        errors: str | None = None,
290        newline: str | None = None,
291    ) -> IO[Any]:
292        """
293        Open the file pointed by this path and return a file object, as
294        the built-in open() function does.
295        """
296        stream = super().open(mode, buffering, encoding, errors, newline)
297        if "r" in mode:
298            self._last_read_time = time.time()
299        return stream
300
301    def write_text(
302        self,
303        data: Any,
304        encoding: Any | None = None,
305        errors: Any | None = None,
306        newline: Any | None = None,
307        parents: bool = True,
308    ) -> int:
309        """Write data to file.
310
311        If a `TypeError` is raised, the function  will attempt to cast `data` to a `str` and try the write again.
312
313        If a `FileNotFoundError` is raised and `parents = True`, `self.parent` will be created.
314        """
315        write = functools.partial(
316            super().write_text,
317            encoding=encoding,
318            errors=errors,
319            newline=newline,
320        )
321        try:
322            return write(data)
323        except TypeError:
324            data = str(data)
325            return write(data)
326        except FileNotFoundError:
327            if parents:
328                self.parent.mkdir(parents=True)
329                return write(data)
330            else:
331                raise
332        except Exception as e:
333            raise
334
335    def write_bytes(self, data: Buffer, parents: bool = True) -> int:
336        """Write bytes to file.
337
338        #### :params:
339
340        `parents`: If `True` and the write operation fails with a `FileNotFoundError`,
341        make the parent directory and retry the write."""
342        try:
343            return super().write_bytes(data)
344        except FileNotFoundError:
345            if parents:
346                self.parent.mkdir(parents=True)
347                return super().write_bytes(data)
348            else:
349                raise
350        except Exception as e:
351            raise
352
353    def append(self, data: str, new_line: bool = True, encoding: Any | None = None):
354        """Append `data` to the file pointed to by this `Pathier` object.
355
356        #### :params:
357
358        `new_line`: If `True`, add `\\n` to `data`.
359
360        `encoding`: The file encoding to use."""
361        if new_line:
362            data += "\n"
363        with self.open("a", encoding=encoding) as file:
364            file.write(data)
365
366    def replace_strings(
367        self,
368        substitutions: Sequence[tuple[str, str]],
369        count: int = -1,
370        encoding: Any | None = None,
371    ):
372        """For each pair in `substitutions`, replace the first string with the second string.
373
374        #### :params:
375
376        `count`: Only replace this many occurences of each pair.
377        By default (`-1`), all occurences are replaced.
378
379        `encoding`: The file encoding to use.
380
381        e.g.
382        >>> path = Pathier("somefile.txt")
383        >>>
384        >>> path.replace([("hello", "yeet"), ("goodbye", "yeehaw")])
385        equivalent to
386        >>> path.write_text(path.read_text().replace("hello", "yeet").replace("goodbye", "yeehaw"))
387        """
388        text = self.read_text(encoding)
389        for sub in substitutions:
390            text = text.replace(sub[0], sub[1], count)
391        self.write_text(text, encoding=encoding)
392
393    def join(self, data: Sequence[str], encoding: Any | None = None, sep: str = "\n"):
394        """Write a list of strings, joined by `sep`, to the file pointed at by this instance.
395
396        Equivalent to `Pathier("somefile.txt").write_text(sep.join(data), encoding=encoding)`
397
398        #### :params:
399
400        `encoding`: The file encoding to use.
401
402        `sep`: The separator to use when joining `data`."""
403        self.write_text(sep.join(data), encoding=encoding)
404
405    def split(self, encoding: Any | None = None, keepends: bool = False) -> list[str]:
406        """Returns the content of the pointed at file as a list of strings, splitting at new line characters.
407
408        Equivalent to `Pathier("somefile.txt").read_text(encoding=encoding).splitlines()`
409
410        #### :params:
411
412        `encoding`: The file encoding to use.
413
414        `keepend`: If `True`, line breaks will be included in returned strings."""
415        return self.read_text(encoding=encoding).splitlines(keepends)
416
417    def json_loads(self, encoding: Any | None = None, errors: Any | None = None) -> Any:
418        """Load json file."""
419        return json.loads(self.read_text(encoding, errors))
420
421    def json_dumps(
422        self,
423        data: Any,
424        encoding: Any | None = None,
425        errors: Any | None = None,
426        newline: Any | None = None,
427        sort_keys: bool = False,
428        indent: Any | None = 2,
429        default: Any | None = str,
430        parents: bool = True,
431    ) -> Any:
432        """Dump `data` to json file."""
433        self.write_text(
434            json.dumps(data, indent=indent, default=default, sort_keys=sort_keys),
435            encoding,
436            errors,
437            newline,
438            parents,
439        )
440
441    def pickle_loads(self) -> Any:
442        """Load pickle file."""
443        return pickle.loads(self.read_bytes())
444
445    def pickle_dumps(self, data: Any):
446        """Dump `data` to pickle file."""
447        self.write_bytes(pickle.dumps(data))
448
449    def toml_loads(self, encoding: Any | None = None, errors: Any | None = None) -> Any:
450        """Load toml file."""
451        return tomlkit.loads(self.read_text(encoding, errors)).unwrap()
452
453    def toml_dumps(
454        self,
455        data: Any,
456        toml_encoders: Sequence[Callable[[Any], Any]] = [str],
457        encoding: Any | None = None,
458        errors: Any | None = None,
459        newline: Any | None = None,
460        sort_keys: bool = False,
461        parents: bool = True,
462    ):
463        """Dump `data` to toml file.
464
465        `toml_encoders` can be a list of functions to call when a value in `data` doesn't map to `tomlkit`'s built in types.
466        By default, anything that `tomlkit` can't convert will be cast to a string. Encoder order matters.
467        e.g. By default any `Pathier` object in `data` will be converted to a string."""
468        encoders: list[Callable[[Any], Any]] = []
469        for toml_encoder in toml_encoders:
470            encoder: Callable[[Any], Any] = lambda x: tomlkit.item(  # type:ignore
471                toml_encoder(x)
472            )
473            encoders.append(encoder)
474            tomlkit.register_encoder(encoder)
475        try:
476            self.write_text(
477                tomlkit.dumps(data, sort_keys),  # type:ignore
478                encoding,
479                errors,
480                newline,
481                parents,
482            )
483        except Exception as e:
484            raise e
485        finally:
486            for encoder in encoders:
487                tomlkit.unregister_encoder(encoder)
488
489    def loads(self, encoding: Any | None = None, errors: Any | None = None) -> Any:
490        """Load a json, toml, or pickle file based off this path's suffix."""
491        match self.suffix:
492            case ".json":
493                return self.json_loads(encoding, errors)
494            case ".toml":
495                return self.toml_loads(encoding, errors)
496            case ".pickle" | ".pkl":
497                return self.pickle_loads()
498            case _:
499                raise ValueError(
500                    f"No load function exists for file type `{self.suffix}`."
501                )
502
503    def dumps(
504        self,
505        data: Any,
506        encoding: Any | None = None,
507        errors: Any | None = None,
508        newline: Any | None = None,
509        sort_keys: bool = False,
510        indent: Any | None = None,
511        default: Any | None = str,
512        toml_encoders: Sequence[Callable[[Any], Any]] = [str],
513        parents: bool = True,
514    ):
515        """Dump `data` to a json or toml file based off this instance's suffix.
516
517        For toml files:
518        `toml_encoders` can be a list of functions to call when a value in `data` doesn't map to `tomlkit`'s built in types.
519        By default, anything that `tomlkit` can't convert will be cast to a string. Encoder order matters.
520        e.g. By default any `Pathier` object in `data` will be converted to a string."""
521        match self.suffix:
522            case ".json":
523                self.json_dumps(
524                    data, encoding, errors, newline, sort_keys, indent, default, parents
525                )
526            case ".toml":
527                self.toml_dumps(
528                    data, toml_encoders, encoding, errors, newline, sort_keys, parents
529                )
530            case ".pickle" | ".pkl":
531                self.pickle_dumps(data)
532            case _:
533                raise ValueError(
534                    f"No dump function exists for file type `{self.suffix}`."
535                )
536
537    def delete(self, missing_ok: bool = True):
538        """Delete the file or folder pointed to by this instance.
539
540        Uses `self.unlink()` if a file and uses `shutil.rmtree()` if a directory."""
541        if self.is_file():
542            self.unlink(missing_ok)
543        elif self.is_dir():
544            shutil.rmtree(self)
545
546    def copy(
547        self, new_path: Self | pathlib.Path | str, overwrite: bool = False
548    ) -> Self:
549        """Copy the path pointed to by this instance
550        to the instance pointed to by `new_path` using `shutil.copyfile`
551        or `shutil.copytree`.
552
553        Returns the new path.
554
555        #### :params:
556
557        `new_path`: The copy destination.
558
559        `overwrite`: If `True`, files already existing in `new_path` will be overwritten.
560        If `False`, only files that don't exist in `new_path` will be copied."""
561        dst = self.__class__(new_path)
562        if self.is_dir():
563            if overwrite or not dst.exists():
564                dst.mkdir()
565                shutil.copytree(self, dst, dirs_exist_ok=True)
566            else:
567                files = self.rglob("*.*")
568                for file in files:
569                    dst = dst.with_name(file.name)
570                    if not dst.exists():
571                        shutil.copyfile(file, dst)
572        elif self.is_file():
573            if overwrite or not dst.exists():
574                shutil.copyfile(self, dst)
575        return dst
576
577    def backup(self, timestamp: bool = False) -> Self | None:
578        """Create a copy of this file or directory with `_backup` appended to the path stem.
579        If the path to be backed up doesn't exist, `None` is returned.
580        Otherwise a `Pathier` object for the backup is returned.
581
582        #### :params:
583
584        `timestamp`: Add a timestamp to the backup name to prevent overriding previous backups.
585
586        >>> path = Pathier("some_file.txt")
587        >>> path.backup()
588        >>> list(path.iterdir())
589        >>> ['some_file.txt', 'some_file_backup.txt']
590        >>> path.backup(True)
591        >>> list(path.iterdir())
592        >>> ['some_file.txt', 'some_file_backup.txt', 'some_file_backup_04-28-2023-06_25_52_PM.txt']
593        """
594        if not self.exists():
595            return None
596        backup_stem = f"{self.stem}_backup"
597        if timestamp:
598            backup_stem = f"{backup_stem}_{datetime.datetime.now().strftime('%m-%d-%Y-%I_%M_%S_%p')}"
599        backup_path = self.with_stem(backup_stem)
600        self.copy(backup_path, True)
601        return backup_path
602
603    def execute(self, command: str = "", args: str = "") -> int:
604        """Make a call to `os.system` using the path pointed to by this Pathier object.
605
606        #### :params:
607
608        `command`: Program/command to precede the path with.
609
610        `args`: Any arguments that should come after the path.
611
612        :returns: The integer output of `os.system`.
613
614        e.g.
615        >>> path = Pathier("mydirectory") / "myscript.py"
616        then
617        >>> path.execute("py", "--iterations 10")
618        equivalent to
619        >>> os.system(f"py {path} --iterations 10")"""
620        return os.system(f"{command} {self} {args}")

Subclasses the standard library pathlib.Path class.

Pathier()
convert_backslashes: bool

If True, when self.__str__()/str(self) is called, string representations will have double backslashes converted to a forward slash.

Only affects Windows paths.

dob: datetime.datetime | None

Returns the creation date of this file or directory as a dateime.datetime object.

age: float | None

Returns the age in seconds of this file or directory.

mod_date: datetime.datetime | None

Returns the modification date of this file or directory as a datetime.datetime object.

mod_delta: float | None

Returns how long ago in seconds this file or directory was modified.

last_read_time: datetime.datetime | None

Returns the last time this object made a call to self.read_text(), self.read_bytes(), or self.open(mode="r"|"rb"). Returns None if the file hasn't been read from.

Note: This property is only relative to the lifetime of this Pathier instance, not the file itself. i.e. This property will reset if you create a new Pathier object pointing to the same file.

modified_since_last_read: bool

Returns True if this file hasn't been read from or has been modified since the last time this object made a call to self.read_text(), self.read_bytes(), or self.open(mode="r"|"rb").

Note: This property is only relative to the lifetime of this Pathier instance, not the file itself. i.e. This property will reset if you create a new Pathier object pointing to the same file.

Caveat:

May not be accurate if the file was modified within a couple of seconds of checking this property. (For instance, on my machine self.mod_date is consistently 1-1.5s in the future from when self.write_text() was called according to time.time().)

size: int

Returns the size in bytes of this file or directory.

If this path doesn't exist, 0 will be returned.

formatted_size: str

The size of this file or directory formatted with self.format_bytes().

@staticmethod
def format_bytes(size: int) -> str:
145    @staticmethod
146    def format_bytes(size: int) -> str:
147        """Format `size` with common file size abbreviations and rounded to two decimal places.
148        >>> 1234 -> "1.23 kb" """
149        unit = "bytes"
150        for unit in ["bytes", "kb", "mb", "gb", "tb", "pb"]:
151            if unit != "bytes":
152                size *= 0.001  # type: ignore
153            if size < 1000 or unit == "pb":
154                break
155        return f"{round(size, 2)} {unit}"

Format size with common file size abbreviations and rounded to two decimal places.

>>> 1234 -> "1.23 kb"
def is_larger(self, path: Self) -> bool:
157    def is_larger(self, path: Self) -> bool:
158        """Returns whether this file or folder is larger than the one pointed to by `path`."""
159        return self.size > path.size

Returns whether this file or folder is larger than the one pointed to by path.

def is_older(self, path: Self) -> bool | None:
161    def is_older(self, path: Self) -> bool | None:
162        """Returns whether this file or folder is older than the one pointed to by `path`.
163
164        Returns `None` if one or both paths don't exist."""
165        return self.dob < path.dob if self.dob and path.dob else None

Returns whether this file or folder is older than the one pointed to by path.

Returns None if one or both paths don't exist.

def modified_more_recently(self, path: Self) -> bool | None:
167    def modified_more_recently(self, path: Self) -> bool | None:
168        """Returns whether this file or folder was modified more recently than the one pointed to by `path`.
169
170        Returns `None` if one or both paths don't exist."""
171        return (
172            self.mod_date > path.mod_date if self.mod_date and path.mod_date else None
173        )

Returns whether this file or folder was modified more recently than the one pointed to by path.

Returns None if one or both paths don't exist.

def mkcwd(self):
176    def mkcwd(self):
177        """Make this path your current working directory."""
178        os.chdir(self)

Make this path your current working directory.

in_PATH: bool

Return True if this path is in sys.path.

def add_to_PATH(self, index: int = 0):
185    def add_to_PATH(self, index: int = 0):
186        """Insert this path into `sys.path` if it isn't already there.
187
188        #### :params:
189
190        `index`: The index of `sys.path` to insert this path at."""
191        path = str(self)
192        if not self.in_PATH:
193            sys.path.insert(index, path)

Insert this path into sys.path if it isn't already there.

:params:

index: The index of sys.path to insert this path at.

def append_to_PATH(self):
195    def append_to_PATH(self):
196        """Append this path to `sys.path` if it isn't already there."""
197        path = str(self)
198        if not self.in_PATH:
199            sys.path.append(path)

Append this path to sys.path if it isn't already there.

def remove_from_PATH(self):
201    def remove_from_PATH(self):
202        """Remove this path from `sys.path` if it's in `sys.path`."""
203        if self.in_PATH:
204            sys.path.remove(str(self))

Remove this path from sys.path if it's in sys.path.

def moveup(self, name: str) -> Self:
214    def moveup(self, name: str) -> Self:
215        """Return a new `Pathier` object that is a parent of this instance.
216
217        `name` is case-sensitive and raises an exception if it isn't in `self.parts`.
218        >>> p = Pathier("C:/some/directory/in/your/system")
219        >>> print(p.moveup("directory"))
220        >>> "C:/some/directory"
221        >>> print(p.moveup("yeet"))
222        >>> "Exception: yeet is not a parent of C:/some/directory/in/your/system" """
223        index = self._get_path_part_rindex(name)
224        if index is None:
225            raise Exception(f"{name} is not a parent of {self}")
226        return self - (len(self.parts) - index - 1)
227        return self.__class__(*(self.parts[: index + 1]))

Return a new Pathier object that is a parent of this instance.

name is case-sensitive and raises an exception if it isn't in self.parts.

>>> p = Pathier("C:/some/directory/in/your/system")
>>> print(p.moveup("directory"))
>>> "C:/some/directory"
>>> print(p.moveup("yeet"))
>>> "Exception: yeet is not a parent of C:/some/directory/in/your/system"
def move_under(self, name: str) -> Self:
240    def move_under(self, name: str) -> Self:
241        """Return a new `Pathier` object such that the stem is one level below the given folder `name`.
242
243        `name` is case-sensitive and raises an exception if it isn't in `self.parts`.
244        >>> p = Pathier("a/b/c/d/e/f/g")
245        >>> print(p.move_under("c"))
246        >>> 'a/b/c/d'"""
247        index = self._get_path_part_rindex(name)
248        if index is None:
249            raise Exception(f"{name} is not a parent of {self}")
250        return self - (len(self.parts) - index - 2)

Return a new Pathier object such that the stem is one level below the given folder name.

name is case-sensitive and raises an exception if it isn't in self.parts.

>>> p = Pathier("a/b/c/d/e/f/g")
>>> print(p.move_under("c"))
>>> 'a/b/c/d'
def separate(self, name: str, keep_name: bool = False) -> Self:
252    def separate(self, name: str, keep_name: bool = False) -> Self:
253        """Return a new `Pathier` object that is the relative child path after `name`.
254
255        `name` is case-sensitive and raises an exception if it isn't in `self.parts`.
256
257        #### :params:
258
259        `keep_name`: If `True`, the returned path will start with `name`.
260        >>> p = Pathier("a/b/c/d/e/f/g")
261        >>> print(p.separate("c"))
262        >>> 'd/e/f/g'
263        >>> print(p.separate("c", True))
264        >>> 'c/d/e/f/g'"""
265        if name not in self.parts:
266            raise Exception(f"{name} is not a parent of {self}")
267        if keep_name:
268            return self.__class__(*self.parts[self.parts.index(name) :])
269        return self.__class__(*self.parts[self.parts.index(name) + 1 :])

Return a new Pathier object that is the relative child path after name.

name is case-sensitive and raises an exception if it isn't in self.parts.

:params:

keep_name: If True, the returned path will start with name.

>>> p = Pathier("a/b/c/d/e/f/g")
>>> print(p.separate("c"))
>>> 'd/e/f/g'
>>> print(p.separate("c", True))
>>> 'c/d/e/f/g'
def mkdir(self, mode: int = 511, parents: bool = True, exist_ok: bool = True):
272    def mkdir(self, mode: int = 511, parents: bool = True, exist_ok: bool = True):
273        """Create this directory.
274
275        Same as `Path().mkdir()` except `parents` and `exist_ok` default to `True` instead of `False`.
276        """
277        super().mkdir(mode, parents, exist_ok)

Create this directory.

Same as Path().mkdir() except parents and exist_ok default to True instead of False.

def touch(self, mode: int = 438, exist_ok: bool = True):
279    def touch(self, mode: int = 438, exist_ok: bool = True):
280        """Create file (and parents if necessary)."""
281        self.parent.mkdir()
282        super().touch(mode, exist_ok)

Create file (and parents if necessary).

def open( self, mode: str = 'r', buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None) -> IO[Any]:
284    def open(  # type: ignore
285        self,
286        mode: str = "r",
287        buffering: int = -1,
288        encoding: str | None = None,
289        errors: str | None = None,
290        newline: str | None = None,
291    ) -> IO[Any]:
292        """
293        Open the file pointed by this path and return a file object, as
294        the built-in open() function does.
295        """
296        stream = super().open(mode, buffering, encoding, errors, newline)
297        if "r" in mode:
298            self._last_read_time = time.time()
299        return stream

Open the file pointed by this path and return a file object, as the built-in open() function does.

def write_text( self, data: Any, encoding: typing.Any | None = None, errors: typing.Any | None = None, newline: typing.Any | None = None, parents: bool = True) -> int:
301    def write_text(
302        self,
303        data: Any,
304        encoding: Any | None = None,
305        errors: Any | None = None,
306        newline: Any | None = None,
307        parents: bool = True,
308    ) -> int:
309        """Write data to file.
310
311        If a `TypeError` is raised, the function  will attempt to cast `data` to a `str` and try the write again.
312
313        If a `FileNotFoundError` is raised and `parents = True`, `self.parent` will be created.
314        """
315        write = functools.partial(
316            super().write_text,
317            encoding=encoding,
318            errors=errors,
319            newline=newline,
320        )
321        try:
322            return write(data)
323        except TypeError:
324            data = str(data)
325            return write(data)
326        except FileNotFoundError:
327            if parents:
328                self.parent.mkdir(parents=True)
329                return write(data)
330            else:
331                raise
332        except Exception as e:
333            raise

Write data to file.

If a TypeError is raised, the function will attempt to cast data to a str and try the write again.

If a FileNotFoundError is raised and parents = True, self.parent will be created.

def write_bytes(self, data: typing_extensions.Buffer, parents: bool = True) -> int:
335    def write_bytes(self, data: Buffer, parents: bool = True) -> int:
336        """Write bytes to file.
337
338        #### :params:
339
340        `parents`: If `True` and the write operation fails with a `FileNotFoundError`,
341        make the parent directory and retry the write."""
342        try:
343            return super().write_bytes(data)
344        except FileNotFoundError:
345            if parents:
346                self.parent.mkdir(parents=True)
347                return super().write_bytes(data)
348            else:
349                raise
350        except Exception as e:
351            raise

Write bytes to file.

:params:

parents: If True and the write operation fails with a FileNotFoundError, make the parent directory and retry the write.

def append( self, data: str, new_line: bool = True, encoding: typing.Any | None = None):
353    def append(self, data: str, new_line: bool = True, encoding: Any | None = None):
354        """Append `data` to the file pointed to by this `Pathier` object.
355
356        #### :params:
357
358        `new_line`: If `True`, add `\\n` to `data`.
359
360        `encoding`: The file encoding to use."""
361        if new_line:
362            data += "\n"
363        with self.open("a", encoding=encoding) as file:
364            file.write(data)

Append data to the file pointed to by this Pathier object.

:params:

new_line: If True, add \n to data.

encoding: The file encoding to use.

def replace_strings( self, substitutions: Sequence[tuple[str, str]], count: int = -1, encoding: typing.Any | None = None):
366    def replace_strings(
367        self,
368        substitutions: Sequence[tuple[str, str]],
369        count: int = -1,
370        encoding: Any | None = None,
371    ):
372        """For each pair in `substitutions`, replace the first string with the second string.
373
374        #### :params:
375
376        `count`: Only replace this many occurences of each pair.
377        By default (`-1`), all occurences are replaced.
378
379        `encoding`: The file encoding to use.
380
381        e.g.
382        >>> path = Pathier("somefile.txt")
383        >>>
384        >>> path.replace([("hello", "yeet"), ("goodbye", "yeehaw")])
385        equivalent to
386        >>> path.write_text(path.read_text().replace("hello", "yeet").replace("goodbye", "yeehaw"))
387        """
388        text = self.read_text(encoding)
389        for sub in substitutions:
390            text = text.replace(sub[0], sub[1], count)
391        self.write_text(text, encoding=encoding)

For each pair in substitutions, replace the first string with the second string.

:params:

count: Only replace this many occurences of each pair. By default (-1), all occurences are replaced.

encoding: The file encoding to use.

e.g.

>>> path = Pathier("somefile.txt")
>>>
>>> path.replace([("hello", "yeet"), ("goodbye", "yeehaw")])
equivalent to
>>> path.write_text(path.read_text().replace("hello", "yeet").replace("goodbye", "yeehaw"))
def join( self, data: Sequence[str], encoding: typing.Any | None = None, sep: str = '\n'):
393    def join(self, data: Sequence[str], encoding: Any | None = None, sep: str = "\n"):
394        """Write a list of strings, joined by `sep`, to the file pointed at by this instance.
395
396        Equivalent to `Pathier("somefile.txt").write_text(sep.join(data), encoding=encoding)`
397
398        #### :params:
399
400        `encoding`: The file encoding to use.
401
402        `sep`: The separator to use when joining `data`."""
403        self.write_text(sep.join(data), encoding=encoding)

Write a list of strings, joined by sep, to the file pointed at by this instance.

Equivalent to Pathier("somefile.txt").write_text(sep.join(data), encoding=encoding)

:params:

encoding: The file encoding to use.

sep: The separator to use when joining data.

def split( self, encoding: typing.Any | None = None, keepends: bool = False) -> list[str]:
405    def split(self, encoding: Any | None = None, keepends: bool = False) -> list[str]:
406        """Returns the content of the pointed at file as a list of strings, splitting at new line characters.
407
408        Equivalent to `Pathier("somefile.txt").read_text(encoding=encoding).splitlines()`
409
410        #### :params:
411
412        `encoding`: The file encoding to use.
413
414        `keepend`: If `True`, line breaks will be included in returned strings."""
415        return self.read_text(encoding=encoding).splitlines(keepends)

Returns the content of the pointed at file as a list of strings, splitting at new line characters.

Equivalent to Pathier("somefile.txt").read_text(encoding=encoding).splitlines()

:params:

encoding: The file encoding to use.

keepend: If True, line breaks will be included in returned strings.

def json_loads( self, encoding: typing.Any | None = None, errors: typing.Any | None = None) -> Any:
417    def json_loads(self, encoding: Any | None = None, errors: Any | None = None) -> Any:
418        """Load json file."""
419        return json.loads(self.read_text(encoding, errors))

Load json file.

def json_dumps( self, data: Any, encoding: typing.Any | None = None, errors: typing.Any | None = None, newline: typing.Any | None = None, sort_keys: bool = False, indent: typing.Any | None = 2, default: typing.Any | None = <class 'str'>, parents: bool = True) -> Any:
421    def json_dumps(
422        self,
423        data: Any,
424        encoding: Any | None = None,
425        errors: Any | None = None,
426        newline: Any | None = None,
427        sort_keys: bool = False,
428        indent: Any | None = 2,
429        default: Any | None = str,
430        parents: bool = True,
431    ) -> Any:
432        """Dump `data` to json file."""
433        self.write_text(
434            json.dumps(data, indent=indent, default=default, sort_keys=sort_keys),
435            encoding,
436            errors,
437            newline,
438            parents,
439        )

Dump data to json file.

def pickle_loads(self) -> Any:
441    def pickle_loads(self) -> Any:
442        """Load pickle file."""
443        return pickle.loads(self.read_bytes())

Load pickle file.

def pickle_dumps(self, data: Any):
445    def pickle_dumps(self, data: Any):
446        """Dump `data` to pickle file."""
447        self.write_bytes(pickle.dumps(data))

Dump data to pickle file.

def toml_loads( self, encoding: typing.Any | None = None, errors: typing.Any | None = None) -> Any:
449    def toml_loads(self, encoding: Any | None = None, errors: Any | None = None) -> Any:
450        """Load toml file."""
451        return tomlkit.loads(self.read_text(encoding, errors)).unwrap()

Load toml file.

def toml_dumps( self, data: Any, toml_encoders: Sequence[Callable[[Any], Any]] = [<class 'str'>], encoding: typing.Any | None = None, errors: typing.Any | None = None, newline: typing.Any | None = None, sort_keys: bool = False, parents: bool = True):
453    def toml_dumps(
454        self,
455        data: Any,
456        toml_encoders: Sequence[Callable[[Any], Any]] = [str],
457        encoding: Any | None = None,
458        errors: Any | None = None,
459        newline: Any | None = None,
460        sort_keys: bool = False,
461        parents: bool = True,
462    ):
463        """Dump `data` to toml file.
464
465        `toml_encoders` can be a list of functions to call when a value in `data` doesn't map to `tomlkit`'s built in types.
466        By default, anything that `tomlkit` can't convert will be cast to a string. Encoder order matters.
467        e.g. By default any `Pathier` object in `data` will be converted to a string."""
468        encoders: list[Callable[[Any], Any]] = []
469        for toml_encoder in toml_encoders:
470            encoder: Callable[[Any], Any] = lambda x: tomlkit.item(  # type:ignore
471                toml_encoder(x)
472            )
473            encoders.append(encoder)
474            tomlkit.register_encoder(encoder)
475        try:
476            self.write_text(
477                tomlkit.dumps(data, sort_keys),  # type:ignore
478                encoding,
479                errors,
480                newline,
481                parents,
482            )
483        except Exception as e:
484            raise e
485        finally:
486            for encoder in encoders:
487                tomlkit.unregister_encoder(encoder)

Dump data to toml file.

toml_encoders can be a list of functions to call when a value in data doesn't map to tomlkit's built in types. By default, anything that tomlkit can't convert will be cast to a string. Encoder order matters. e.g. By default any Pathier object in data will be converted to a string.

def loads( self, encoding: typing.Any | None = None, errors: typing.Any | None = None) -> Any:
489    def loads(self, encoding: Any | None = None, errors: Any | None = None) -> Any:
490        """Load a json, toml, or pickle file based off this path's suffix."""
491        match self.suffix:
492            case ".json":
493                return self.json_loads(encoding, errors)
494            case ".toml":
495                return self.toml_loads(encoding, errors)
496            case ".pickle" | ".pkl":
497                return self.pickle_loads()
498            case _:
499                raise ValueError(
500                    f"No load function exists for file type `{self.suffix}`."
501                )

Load a json, toml, or pickle file based off this path's suffix.

def dumps( self, data: Any, encoding: typing.Any | None = None, errors: typing.Any | None = None, newline: typing.Any | None = None, sort_keys: bool = False, indent: typing.Any | None = None, default: typing.Any | None = <class 'str'>, toml_encoders: Sequence[Callable[[Any], Any]] = [<class 'str'>], parents: bool = True):
503    def dumps(
504        self,
505        data: Any,
506        encoding: Any | None = None,
507        errors: Any | None = None,
508        newline: Any | None = None,
509        sort_keys: bool = False,
510        indent: Any | None = None,
511        default: Any | None = str,
512        toml_encoders: Sequence[Callable[[Any], Any]] = [str],
513        parents: bool = True,
514    ):
515        """Dump `data` to a json or toml file based off this instance's suffix.
516
517        For toml files:
518        `toml_encoders` can be a list of functions to call when a value in `data` doesn't map to `tomlkit`'s built in types.
519        By default, anything that `tomlkit` can't convert will be cast to a string. Encoder order matters.
520        e.g. By default any `Pathier` object in `data` will be converted to a string."""
521        match self.suffix:
522            case ".json":
523                self.json_dumps(
524                    data, encoding, errors, newline, sort_keys, indent, default, parents
525                )
526            case ".toml":
527                self.toml_dumps(
528                    data, toml_encoders, encoding, errors, newline, sort_keys, parents
529                )
530            case ".pickle" | ".pkl":
531                self.pickle_dumps(data)
532            case _:
533                raise ValueError(
534                    f"No dump function exists for file type `{self.suffix}`."
535                )

Dump data to a json or toml file based off this instance's suffix.

For toml files: toml_encoders can be a list of functions to call when a value in data doesn't map to tomlkit's built in types. By default, anything that tomlkit can't convert will be cast to a string. Encoder order matters. e.g. By default any Pathier object in data will be converted to a string.

def delete(self, missing_ok: bool = True):
537    def delete(self, missing_ok: bool = True):
538        """Delete the file or folder pointed to by this instance.
539
540        Uses `self.unlink()` if a file and uses `shutil.rmtree()` if a directory."""
541        if self.is_file():
542            self.unlink(missing_ok)
543        elif self.is_dir():
544            shutil.rmtree(self)

Delete the file or folder pointed to by this instance.

Uses self.unlink() if a file and uses shutil.rmtree() if a directory.

def copy( self, new_path: Union[Self, pathlib.Path, str], overwrite: bool = False) -> Self:
546    def copy(
547        self, new_path: Self | pathlib.Path | str, overwrite: bool = False
548    ) -> Self:
549        """Copy the path pointed to by this instance
550        to the instance pointed to by `new_path` using `shutil.copyfile`
551        or `shutil.copytree`.
552
553        Returns the new path.
554
555        #### :params:
556
557        `new_path`: The copy destination.
558
559        `overwrite`: If `True`, files already existing in `new_path` will be overwritten.
560        If `False`, only files that don't exist in `new_path` will be copied."""
561        dst = self.__class__(new_path)
562        if self.is_dir():
563            if overwrite or not dst.exists():
564                dst.mkdir()
565                shutil.copytree(self, dst, dirs_exist_ok=True)
566            else:
567                files = self.rglob("*.*")
568                for file in files:
569                    dst = dst.with_name(file.name)
570                    if not dst.exists():
571                        shutil.copyfile(file, dst)
572        elif self.is_file():
573            if overwrite or not dst.exists():
574                shutil.copyfile(self, dst)
575        return dst

Copy the path pointed to by this instance to the instance pointed to by new_path using shutil.copyfile or shutil.copytree.

Returns the new path.

:params:

new_path: The copy destination.

overwrite: If True, files already existing in new_path will be overwritten. If False, only files that don't exist in new_path will be copied.

def backup(self, timestamp: bool = False) -> Optional[Self]:
577    def backup(self, timestamp: bool = False) -> Self | None:
578        """Create a copy of this file or directory with `_backup` appended to the path stem.
579        If the path to be backed up doesn't exist, `None` is returned.
580        Otherwise a `Pathier` object for the backup is returned.
581
582        #### :params:
583
584        `timestamp`: Add a timestamp to the backup name to prevent overriding previous backups.
585
586        >>> path = Pathier("some_file.txt")
587        >>> path.backup()
588        >>> list(path.iterdir())
589        >>> ['some_file.txt', 'some_file_backup.txt']
590        >>> path.backup(True)
591        >>> list(path.iterdir())
592        >>> ['some_file.txt', 'some_file_backup.txt', 'some_file_backup_04-28-2023-06_25_52_PM.txt']
593        """
594        if not self.exists():
595            return None
596        backup_stem = f"{self.stem}_backup"
597        if timestamp:
598            backup_stem = f"{backup_stem}_{datetime.datetime.now().strftime('%m-%d-%Y-%I_%M_%S_%p')}"
599        backup_path = self.with_stem(backup_stem)
600        self.copy(backup_path, True)
601        return backup_path

Create a copy of this file or directory with _backup appended to the path stem. If the path to be backed up doesn't exist, None is returned. Otherwise a Pathier object for the backup is returned.

:params:

timestamp: Add a timestamp to the backup name to prevent overriding previous backups.

>>> path = Pathier("some_file.txt")
>>> path.backup()
>>> list(path.iterdir())
>>> ['some_file.txt', 'some_file_backup.txt']
>>> path.backup(True)
>>> list(path.iterdir())
>>> ['some_file.txt', 'some_file_backup.txt', 'some_file_backup_04-28-2023-06_25_52_PM.txt']
def execute(self, command: str = '', args: str = '') -> int:
603    def execute(self, command: str = "", args: str = "") -> int:
604        """Make a call to `os.system` using the path pointed to by this Pathier object.
605
606        #### :params:
607
608        `command`: Program/command to precede the path with.
609
610        `args`: Any arguments that should come after the path.
611
612        :returns: The integer output of `os.system`.
613
614        e.g.
615        >>> path = Pathier("mydirectory") / "myscript.py"
616        then
617        >>> path.execute("py", "--iterations 10")
618        equivalent to
619        >>> os.system(f"py {path} --iterations 10")"""
620        return os.system(f"{command} {self} {args}")

Make a call to os.system using the path pointed to by this Pathier object.

:params:

command: Program/command to precede the path with.

args: Any arguments that should come after the path.

:returns: The integer output of os.system.

e.g.

>>> path = Pathier("mydirectory") / "myscript.py"
then
>>> path.execute("py", "--iterations 10")
equivalent to
>>> os.system(f"py {path} --iterations 10")
Inherited Members
pathlib.Path
cwd
home
samefile
iterdir
glob
rglob
absolute
resolve
stat
owner
group
read_bytes
read_text
chmod
lchmod
rmdir
lstat
rename
replace
exists
is_dir
is_file
is_mount
is_block_device
is_char_device
is_fifo
is_socket
expanduser
pathlib.PurePath
as_posix
as_uri
drive
root
anchor
name
suffix
suffixes
stem
with_name
with_stem
with_suffix
relative_to
is_relative_to
parts
joinpath
parent
parents
is_absolute
is_reserved
match
Pathy = pathier.Pathier | pathlib.Path
Pathish = pathier.Pathier | pathlib.Path | str