Skip to content

file

Type Aliases:

Classes:

  • SPath

    Modified version of pathlib.Path

Attributes:

FileDescriptor module-attribute

FileDescriptor: TypeAlias = int

FilePathType module-attribute

FilePathType: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes]

OpenBinaryMode module-attribute

OpenBinaryModeReading module-attribute

OpenBinaryModeReading: TypeAlias = Literal[
    "rb", "br", "rbU", "rUb", "Urb", "brU", "bUr", "Ubr"
]

OpenBinaryModeUpdating module-attribute

OpenBinaryModeUpdating: TypeAlias = Literal[
    "rb+",
    "r+b",
    "+rb",
    "br+",
    "b+r",
    "+br",
    "wb+",
    "w+b",
    "+wb",
    "bw+",
    "b+w",
    "+bw",
    "ab+",
    "a+b",
    "+ab",
    "ba+",
    "b+a",
    "+ba",
    "xb+",
    "x+b",
    "+xb",
    "bx+",
    "b+x",
    "+bx",
]

OpenBinaryModeWriting module-attribute

OpenBinaryModeWriting: TypeAlias = Literal['wb', 'bw', 'ab', 'ba', 'xb', 'bx']

OpenTextMode module-attribute

OpenTextModeReading module-attribute

OpenTextModeReading: TypeAlias = Literal[
    "r", "rt", "tr", "U", "rU", "Ur", "rtU", "rUt", "Urt", "trU", "tUr", "Utr"
]

OpenTextModeUpdating module-attribute

OpenTextModeUpdating: TypeAlias = Literal[
    "r+",
    "+r",
    "rt+",
    "r+t",
    "+rt",
    "tr+",
    "t+r",
    "+tr",
    "w+",
    "+w",
    "wt+",
    "w+t",
    "+wt",
    "tw+",
    "t+w",
    "+tw",
    "a+",
    "+a",
    "at+",
    "a+t",
    "+at",
    "ta+",
    "t+a",
    "+ta",
    "x+",
    "+x",
    "xt+",
    "x+t",
    "+xt",
    "tx+",
    "t+x",
    "+tx",
]

OpenTextModeWriting module-attribute

OpenTextModeWriting: TypeAlias = Literal[
    "w", "wt", "tw", "a", "at", "ta", "x", "xt", "tx"
]

SPathLike

SPathLike = str | PathLike[str]

SPath

Bases: Path

Modified version of pathlib.Path

Methods:

  • append_to_stem

    Append a suffix to the stem of the path

  • copy_dir

    Copy the directory to the specified destination.

  • fglob

    Glob the path and return the first match.

  • find_newest_file

    Find the most recently modified file matching the given pattern in the directory.

  • format

    Format the path with the given arguments.

  • get_folder

    Get the folder of the path.

  • get_size

    Get the size of the file or directory in bytes.

  • is_empty_dir

    Check if the directory is empty.

  • is_executable

    Check if the path is executable.

  • lglob

    Glob the path and return the list of paths.

  • mkdirp

    Make the dir path with its parents.

  • move_dir

    Move the directory to the specified destination.

  • read_lines

    Read the file and return its lines.

  • rmdirs

    Remove the dir path with its contents.

  • to_str

    Cast the path to a string.

  • write_lines

    Open the file and write the given lines.

append_to_stem

append_to_stem(suffixes: str | Iterable[str], sep: str = '_') -> SPath

Append a suffix to the stem of the path

Source code in jetpytools/types/file.py
152
153
154
155
156
157
def append_to_stem(self, suffixes: str | Iterable[str], sep: str = "_") -> SPath:
    """Append a suffix to the stem of the path"""

    from ..functions import to_arr

    return self.with_stem(sep.join([self.stem, *to_arr(suffixes)]))

copy_dir

copy_dir(dst: SPath) -> SPath

Copy the directory to the specified destination.

Source code in jetpytools/types/file.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def copy_dir(self, dst: SPath) -> SPath:
    """Copy the directory to the specified destination."""

    if not self.is_dir():
        from ..exceptions import PathIsNotADirectoryError

        raise PathIsNotADirectoryError('The given path, "{self}" is not a directory!', self.copy_dir)

    dst.mkdirp()

    import shutil

    shutil.copytree(self, dst, dirs_exist_ok=True)

    return SPath(dst)

fglob

fglob(pattern: str = '*') -> SPath | None

Glob the path and return the first match.

Source code in jetpytools/types/file.py
201
202
203
204
205
206
207
208
209
210
def fglob(self, pattern: str = "*") -> SPath | None:
    """Glob the path and return the first match."""
    import fnmatch

    for root, dirs, files in walk(self):
        for name in dirs + files:
            if fnmatch.fnmatch(name, pattern):
                return SPath(path.join(root, name))

    return None

find_newest_file

find_newest_file(pattern: str = '*') -> SPath | None

Find the most recently modified file matching the given pattern in the directory.

Source code in jetpytools/types/file.py
212
213
214
215
216
217
218
219
220
221
222
def find_newest_file(self, pattern: str = "*") -> SPath | None:
    """Find the most recently modified file matching the given pattern in the directory."""

    matching_files = self.get_folder().glob(pattern)

    try:
        next(matching_files)
    except StopIteration:
        return None

    return max(matching_files, key=lambda p: p.stat().st_mtime)

format

format(*args: Any, **kwargs: Any) -> SPath

Format the path with the given arguments.

Source code in jetpytools/types/file.py
104
105
106
107
def format(self, *args: Any, **kwargs: Any) -> SPath:
    """Format the path with the given arguments."""

    return SPath(self.to_str().format(*args, **kwargs))

get_folder

get_folder() -> SPath

Get the folder of the path.

Source code in jetpytools/types/file.py
114
115
116
117
118
119
120
121
122
def get_folder(self) -> SPath:
    """Get the folder of the path."""

    folder_path = self.resolve()

    if folder_path.is_dir():
        return folder_path

    return SPath(path.dirname(folder_path))

get_size

get_size() -> int

Get the size of the file or directory in bytes.

Source code in jetpytools/types/file.py
224
225
226
227
228
229
230
231
232
233
234
235
def get_size(self) -> int:
    """Get the size of the file or directory in bytes."""

    if not self.exists():
        from ..exceptions import FileNotExistsError

        raise FileNotExistsError('The given path, "{self}" is not a file or directory!', self.get_size)

    if self.is_file():
        return self.stat().st_size

    return sum(f.stat().st_size for f in self.rglob("*") if f.is_file())

is_empty_dir

is_empty_dir() -> bool

Check if the directory is empty.

Source code in jetpytools/types/file.py
159
160
161
162
def is_empty_dir(self) -> bool:
    """Check if the directory is empty."""

    return self.is_dir() and not any(self.iterdir())

is_executable

is_executable() -> bool

Check if the path is executable.

Source code in jetpytools/types/file.py
237
238
239
240
def is_executable(self) -> bool:
    """Check if the path is executable."""

    return access(self.to_str(), X_OK)

lglob

lglob(pattern: str = '*') -> list[SPath]

Glob the path and return the list of paths.

Source code in jetpytools/types/file.py
196
197
198
199
def lglob(self, pattern: str = "*") -> list[SPath]:
    """Glob the path and return the list of paths."""

    return list(map(SPath, self.glob(pattern)))

mkdirp

mkdirp(mode: int = 511) -> None

Make the dir path with its parents.

Source code in jetpytools/types/file.py
124
125
126
127
def mkdirp(self, mode: int = 0o777) -> None:
    """Make the dir path with its parents."""

    return self.get_folder().mkdir(mode, True, True)

move_dir

move_dir(dst: SPath, *, mode: int = 511) -> None

Move the directory to the specified destination.

Source code in jetpytools/types/file.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def move_dir(self, dst: SPath, *, mode: int = 0o777) -> None:
    """Move the directory to the specified destination."""

    dst.mkdir(mode, True, True)

    for file in listdir(self):
        src_file = self / file
        dst_file = dst / file

        if dst_file.exists():
            src_file.unlink()
        else:
            src_file.rename(dst_file)

    self.rmdir()

read_lines

read_lines(
    encoding: str | None = None,
    errors: str | None = None,
    keepends: bool = False,
) -> list[str]

Read the file and return its lines.

Source code in jetpytools/types/file.py
140
141
142
143
def read_lines(self, encoding: str | None = None, errors: str | None = None, keepends: bool = False) -> list[str]:
    """Read the file and return its lines."""

    return super().read_text(encoding, errors).splitlines(keepends)

rmdirs

rmdirs(missing_ok: bool = False, ignore_errors: bool = True) -> None

Remove the dir path with its contents.

Source code in jetpytools/types/file.py
129
130
131
132
133
134
135
136
137
138
def rmdirs(self, missing_ok: bool = False, ignore_errors: bool = True) -> None:
    """Remove the dir path with its contents."""

    import shutil

    try:
        return shutil.rmtree(str(self.get_folder()), ignore_errors)
    except FileNotFoundError:
        if not missing_ok:
            raise

to_str

to_str() -> str

Cast the path to a string.

Source code in jetpytools/types/file.py
109
110
111
112
def to_str(self) -> str:
    """Cast the path to a string."""

    return str(self)

write_lines

write_lines(
    data: Iterable[str],
    encoding: str | None = None,
    errors: str | None = None,
    newline: str | None = None,
) -> int

Open the file and write the given lines.

Source code in jetpytools/types/file.py
145
146
147
148
149
150
def write_lines(
    self, data: Iterable[str], encoding: str | None = None, errors: str | None = None, newline: str | None = None
) -> int:
    """Open the file and write the given lines."""

    return super().write_text("\n".join(data), encoding, errors, newline)