Skip to content

file: and data:

uripath.schemes.FileURIPath(*uris, **options)

Bases: DelegatingURIPath

file: scheme: a URIPath wrapping a LocalPath (filepath), delegating all I/O to it.

Source code in src/uripath/_uri.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def __init__(self, *uris: URILike, **options):
    if options:
        self._check_options(options)
    if self._raw_uris or self._initiated:
        return
    _uris: list[str | URI] = []
    for uri in uris:
        if uri is None or (isinstance(uri, (str, bytes)) and not uri):
            uri = ""
        if isinstance(uri, URI):
            _uris.append(uri)
        elif isinstance(uri, (_pathlib.Path, Path)):
            try:
                uri = uri.as_uri()
            except ValueError:
                # as_uri() raises ValueError for a relative path, which
                # joins like a relative PurePath (see _RelativeLocalPath).
                uri = _RelativeLocalPath(_uriencode(uri.as_posix(), safe="/"))
            _uris.append(uri)
        elif isinstance(uri, (_pathlib.PurePath, Pathname)):
            _uris.append(_path_reference(uri.as_posix()))
        elif hasattr(uri, "as_uri"):
            path = uri.as_uri
            if callable(path):
                path = path()
            _uris.append(path)
        elif isinstance(uri, str):
            _uris.append(uri)
        elif isinstance(uri, bytes):
            _uris.append(uri.decode())
        else:
            path = None
            try:
                path = os.fspath(uri)
            except (TypeError, NotImplementedError):
                pass
            if not isinstance(path, str):
                raise TypeError(
                    "argument should be a str or an os.PathLike "
                    "object where __fspath__ returns a str, "
                    f"not {type(uri).__name__!r}"
                )
            # Only __fspath__ is guaranteed here -- posix-normalize the
            # string itself rather than assuming an as_posix() method.
            posix = _pathlib.PurePath(path).as_posix()
            _uris.append(_path_reference(posix))
    self._raw_uris = _uris

__SCHEMES = ('file',) class-attribute instance-attribute

__slots__ = () class-attribute instance-attribute

filepath property

parent property

is_absolute()

Also True for a Windows drive path ("C:/x"), which _init() stores without the "/" a URI path gets in front of it. "C:" alone is drive-relative, as for PureWindowsPath.

Source code in src/uripath/schemes/_file.py
109
110
111
112
113
114
115
116
117
118
def is_absolute(self):
    """Also True for a Windows drive path ("C:/x"), which `_init()`
    stores without the "/" a URI path gets in front of it. "C:" alone is
    drive-relative, as for `PureWindowsPath`."""
    path = self.path
    if _os.name == "nt":
        drive, sep, _ = path.partition("/")
        if is_drive(drive):
            return bool(sep)
    return super().is_absolute()

is_junction()

Source code in src/uripath/schemes/_file.py
151
152
def is_junction(self) -> bool:
    return self.filepath.is_junction()

is_mount()

Source code in src/uripath/schemes/_file.py
154
155
def is_mount(self) -> bool:
    return self.filepath.is_mount()

mkdir(mode=511, parents=False, exist_ok=False)

Source code in src/uripath/schemes/_file.py
165
166
def mkdir(self, mode=511, parents=False, exist_ok=False):
    return self.filepath.mkdir(mode, parents, exist_ok)

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)

Source code in src/uripath/schemes/_file.py
162
163
def open(self, mode="r", buffering=-1, encoding=None, errors=None, newline=None):
    return self.filepath.open(mode, buffering, encoding, errors, newline)

rename(target)

Source code in src/uripath/schemes/_file.py
176
177
178
179
180
181
182
183
184
185
186
def rename(self, target: FsPathLike | str):
    # Through `_rename_target()` like every scheme: a relative str is a sibling rename
    # (not relative to the process cwd), a local path is accepted, and a remote URI
    # raises NotImplementedError so move() copies.
    dest = self._rename_target(target)
    if not isinstance(dest, FileURIPath):
        dest = self._from_parsed_parts(
            dest.source or self.source, dest.path, None, None
        )
    self.filepath.rename(dest.filepath)
    return dest

stat(*, follow_symlinks=True)

Source code in src/uripath/schemes/_file.py
157
158
159
160
def stat(self, *, follow_symlinks=True):
    # LocalPath.stat() itself shims the 3.10+-only follow_symlinks= kwarg
    # for pathlib.Path (see fspath.py), so just delegate.
    return self.filepath.stat(follow_symlinks=follow_symlinks)

touch(mode=None, exist_ok=True)

Source code in src/uripath/schemes/_file.py
168
169
170
171
172
173
174
def touch(self, mode=None, exist_ok=True):
    # pathlib's touch: the mode goes through os.open(), so the umask
    # applies, and an existing file's mtime is bumped. The generic
    # Path.touch can do neither.
    if mode is None:
        return self.filepath.touch(exist_ok=exist_ok)
    return self.filepath.touch(mode, exist_ok)

with_segments(*segments)

Source code in src/uripath/schemes/_file.py
82
83
84
85
86
87
88
89
def with_segments(self, *segments):
    # A Windows path string separates its names with backslashes.
    if _os.name == "nt":
        segments = tuple(
            item.replace("\\", "/") if isinstance(item, str) else item
            for item in segments
        )
    return super().with_segments(*segments)

uripath.schemes.DataURIPath(*uris, **options)

Bases: URIPath

data: scheme (RFC 2397): a read-only "file" whose entire content is embedded in the URI itself (data:[<mediatype>][;base64],<data>) -- no filesystem, no directories, no backend/connection. RFC 2397 has no query, so an unescaped ? and what follows it are payload; a # starts the fragment, as in any URI, and is not.

Source code in src/uripath/_uri.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def __init__(self, *uris: URILike, **options):
    if options:
        self._check_options(options)
    if self._raw_uris or self._initiated:
        return
    _uris: list[str | URI] = []
    for uri in uris:
        if uri is None or (isinstance(uri, (str, bytes)) and not uri):
            uri = ""
        if isinstance(uri, URI):
            _uris.append(uri)
        elif isinstance(uri, (_pathlib.Path, Path)):
            try:
                uri = uri.as_uri()
            except ValueError:
                # as_uri() raises ValueError for a relative path, which
                # joins like a relative PurePath (see _RelativeLocalPath).
                uri = _RelativeLocalPath(_uriencode(uri.as_posix(), safe="/"))
            _uris.append(uri)
        elif isinstance(uri, (_pathlib.PurePath, Pathname)):
            _uris.append(_path_reference(uri.as_posix()))
        elif hasattr(uri, "as_uri"):
            path = uri.as_uri
            if callable(path):
                path = path()
            _uris.append(path)
        elif isinstance(uri, str):
            _uris.append(uri)
        elif isinstance(uri, bytes):
            _uris.append(uri.decode())
        else:
            path = None
            try:
                path = os.fspath(uri)
            except (TypeError, NotImplementedError):
                pass
            if not isinstance(path, str):
                raise TypeError(
                    "argument should be a str or an os.PathLike "
                    "object where __fspath__ returns a str, "
                    f"not {type(uri).__name__!r}"
                )
            # Only __fspath__ is guaranteed here -- posix-normalize the
            # string itself rather than assuming an as_posix() method.
            posix = _pathlib.PurePath(path).as_posix()
            _uris.append(_path_reference(posix))
    self._raw_uris = _uris

charset property

The charset the media type declares (charset=utf-8, quotes removed), or "utf-8" when it declares none: a text payload is read in it by open() and read_text() unless encoding= says otherwise. UTF-8 reads what the RFC's US-ASCII default names, and more.

mediatype property

The declared media type. Without a type/subtype, RFC 2397 implies "text/plain": a bare header gives "text/plain;charset=US-ASCII", and parameters alone (";charset=utf-8") are given that type.

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)

Source code in src/uripath/schemes/_data.py
66
67
68
69
def open(self, mode="r", buffering=-1, encoding=None, errors=None, newline=None):
    if encoding is None and "b" not in mode:
        encoding = self.charset
    return super().open(mode, buffering, encoding, errors, newline)

stat(*, follow_symlinks=True)

Source code in src/uripath/schemes/_data.py
87
88
def stat(self, *, follow_symlinks=True):
    return FileStat(st_size=len(self._content()), is_dir=False)