API reference

LocalFileSystem

Local filesystem backed by the Rust LocalFs implementation.

LocalFile

File-like wrapper delegating to the Rust RustLocalFile.

S3FileSystem

S3 filesystem backed by the Rust S3Fs implementation.

S3File

File-like wrapper delegating to the Rust RustS3File.

FileInfo

Python-visible file metadata, analogous to the dict returned by fsspec's info().

FileType

Python-visible enum for file types.

Filesystems

class fsspec_rs.LocalFileSystem(*args, **kwargs)[source]

Bases: FileSystem

Local filesystem backed by the Rust LocalFs implementation.

The protocol is registered as ("file-rs", "local-rs") so it can coexist with the pure-Python fsspec.implementations.local.LocalFileSystem which owns the ("file", "local") protocol names.

protocol: str | tuple[str, ...] = ('file-rs', 'local-rs')
local_file = True
unstrip_protocol(path)[source]

Format FS-specific path to generic, including protocol

ls(path: str, detail: bool = True, **kwargs)[source]

List objects at path.

This should include subdirectories and files at that location. The difference between a file and a directory must be clear when details are requested.

The specific keys, or perhaps a FileInfo class, or similar, is TBD, but must be consistent across implementations. Must include:

  • full path to the entry (without protocol)

  • size of the entry, in bytes. If the value cannot be determined, will be None.

  • type of entry, “file”, “directory” or other

Additional information may be present, appropriate to the file-system, e.g., generation, checksum, etc.

May use refresh=True|False to allow use of self._ls_from_cache to check for a saved listing and avoid calling the backend. This would be common where listing may be expensive.

Parameters:
  • path (str)

  • detail (bool) – if True, gives a list of dictionaries, where each is the same as the result of info(path). If False, gives a list of paths (str).

  • kwargs (may have additional backend-specific options, such as version) – information

Returns:

  • List of strings if detail is False, or list of directory information

  • dicts if detail is True.

info(path: str, **kwargs)[source]

Give details of entry at path

Returns a single dictionary, with exactly the same information as ls would with detail=True.

The default implementation calls ls and could be overridden by a shortcut. kwargs are passed on to `ls().

Some file systems might not be able to measure the file’s size, in which case, the returned dict will include 'size': None.

Returns:

  • dict with keys (name (full path in the FS), size (in bytes), type (file,)

  • directory, or something else) and other FS-specific keys.

mkdir(path: str, create_parents: bool = True, **kwargs)[source]

Create directory entry at path

For systems that don’t have true directories, may create an for this instance only and not touch the real filesystem

Parameters:
  • path (str) – location

  • create_parents (bool) – if True, this is equivalent to makedirs

  • kwargs – may be permissions, etc.

makedirs(path: str, exist_ok: bool = False)[source]

Recursively make directories

Creates directory at path and any intervening required directories. Raises exception if, for instance, the path already exists but is a file.

Parameters:
  • path (str) – leaf directory name

  • exist_ok (bool (False)) – If False, will error if the target already exists

rmdir(path: str)[source]

Remove a directory, if empty

rm_file(path: str)[source]

Delete a file

rm(path, recursive: bool = False, maxdepth=None)[source]

Delete files or directories.

Parameters:
  • path (str or list of str) – Files or directories to delete.

  • recursive (bool) – If True, recursively delete directories and their contents.

  • maxdepth (int or None) – Depth to pass to walk for finding files to delete, if recursive. If None, there will be no limit and infinite recursion may be possible.

cp_file(path1: str, path2: str, **kwargs)[source]
copy(path1: str, path2: str, recursive: bool = False, **kwargs)[source]

Copy within two locations in the filesystem

on_error“raise”, “ignore”

If raise, any not-found exceptions will be raised; if ignore any not-found exceptions will cause the path to be skipped; defaults to raise unless recursive is true, where the default is ignore

mv(path1: str, path2: str, **kwargs)[source]

Move file(s) from one location to another

exists(path: str, **kwargs) → bool[source]

Is there a file at the given path

isdir(path: str) → bool[source]

Is this entry directory-like?

isfile(path: str) → bool[source]

Is this entry file-like?

size(path: str) → int[source]

Size in bytes of file

read(path: str, start=None, end=None, condition: Match | Missing | None = None) → ReadResult[source]
write(path: str, data: bytes, condition: Match | Missing | None = None) → WriteResult[source]
read_ranges(path: str, ranges: Sequence[tuple[int | None, int | None]], *, condition: Match | Missing | None = None, max_gap: int = 65536, max_request_size: int = 8388608, max_concurrency: int = 8) → RangeReadResult[source]
cat_ranges(paths, starts, ends, max_gap=None, on_error='return', **kwargs)[source]

Get the contents of byte ranges from one or more files

Parameters:
  • paths (list) – A list of of filepaths on this filesystems

  • starts (int or list) – Bytes limits of the read. If using a single int, the same value will be used to read all the specified files.

  • ends (int or list) – Bytes limits of the read. If using a single int, the same value will be used to read all the specified files.

io_capabilities() → IoCapabilities[source]
cat_file(path: str, start=None, end=None, condition: Match | Missing | None = None, **kwargs) → bytes[source]

Get the content of a file

Parameters:
  • path (URL of file on this filesystems)

  • start (int) – Bytes limits of the read. If negative, backwards from end, like usual python slices. Either can be None for start or end of file, respectively

  • end (int) – Bytes limits of the read. If negative, backwards from end, like usual python slices. Either can be None for start or end of file, respectively

  • kwargs (passed to open().)

pipe_file(path: str, value: bytes, condition: Match | Missing | None = None, **kwargs)[source]

Set the bytes of given file

head(path: str, size: int = 1024) → bytes[source]

Get the first size bytes from file

tail(path: str, size: int = 1024) → bytes[source]

Get the last size bytes from file

touch(path: str, truncate: bool = True, **kwargs)[source]

Create empty file, or update timestamp

Parameters:
  • path (str) – file location

  • truncate (bool) – If True, always set file size to 0; if False, update timestamp and leave file unchanged, if backend allows this

walk(path: str, maxdepth=None, topdown: bool = True, **kwargs)[source]

Return all files under the given path.

List all files, recursing into subdirectories; output is iterator-style, like os.walk(). For a simple list of files, find() is available.

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False has no effect. (see os.walk)

Note that the “files” outputted will include anything that is not a directory, such as links.

Parameters:
  • path (str) – Root to recurse into

  • maxdepth (int) – Maximum recursion depth. None means limitless, but not recommended on link-based file-systems.

  • topdown (bool (True)) – Whether to walk the directory tree from the top downwards or from the bottom upwards.

  • on_error ("omit", "raise", a callable) – if omit (default), path with exception will simply be empty; If raise, an underlying exception will be raised; if callable, it will be called with a single OSError instance as argument

  • kwargs (passed to ls)

find(path: str, maxdepth=None, withdirs: bool = False, **kwargs)[source]

List all files below path.

Like posix find command without conditions

Parameters:
  • path (str)

  • maxdepth (int or None) – If not None, the maximum number of levels to descend

  • withdirs (bool) – Whether to include directory paths in the output. This is True when used by glob, but users usually only want files.

  • ls. (kwargs are passed to)

du(path: str, total: bool = True, maxdepth=None, **kwargs)[source]

Space used by files and optionally directories within a path

Directory size does not include the size of its contents.

Parameters:
  • path (str)

  • total (bool) – Whether to sum all the file sizes

  • maxdepth (int or None) – Maximum number of directory levels to descend, None for unlimited.

  • withdirs (bool) – Whether to include directory paths in the output.

  • kwargs (passed to find)

Returns:

  • Dict of {path (size} if total=False, or int otherwise, where numbers)

  • refer to bytes used.

read_text(path: str, encoding=None, errors=None, newline=None, **kwargs) → str[source]

Get the contents of the file as a string.

Parameters:
  • path (str) – URL of file on this filesystems

  • encoding (same as open.)

  • errors (same as open.)

  • newline (same as open.)

write_text(path: str, value: str, encoding=None, errors=None, newline=None, **kwargs)[source]

Write the text to the given file.

An existing file will be overwritten.

Parameters:
  • path (str) – URL of file on this filesystems

  • value (str) – Text to write.

  • encoding (same as open.)

  • errors (same as open.)

  • newline (same as open.)

get_file(rpath: str, lpath: str, **kwargs)[source]

Copy single remote file to local

put_file(lpath: str, rpath: str, **kwargs)[source]

Copy single file to remote

cat(path, recursive=False, on_error='raise', **kwargs)

Fetch (potentially multiple) paths’ contents

Parameters:
  • recursive (bool) – If True, assume the path(s) are directories, and get all the contained files

  • on_error ("raise", "omit", "return") – If raise, an underlying exception will be raised (converted to KeyError if the type is in self.missing_exceptions); if omit, keys with exception will simply not be included in the output; if “return”, all keys are included in the output, but the value will be bytes or an exception instance.

  • kwargs (passed to cat_file)

Returns:

  • dict of {path (contents} if there are multiple paths)

  • or the path has been otherwise expanded

cp(path1, path2, **kwargs)

Alias of AbstractFileSystem.copy.

disk_usage(path, total=True, maxdepth=None, **kwargs)

Alias of AbstractFileSystem.du.

download(rpath, lpath, recursive=False, **kwargs)

Alias of AbstractFileSystem.get.

expand_path(path, recursive=False, maxdepth=None, assume_literal=False, **kwargs)

Turn one or more globs or directories into a list of all matching paths to files or directories.

kwargs are passed to glob or find, which may in turn call ls

get(rpath, lpath, recursive=False, callback=<fsspec.callbacks.NoOpCallback object>, maxdepth=None, **kwargs)

Copy file(s) to local.

Copies a specific file or tree of files (if recursive=True). If lpath ends with a “/”, it will be assumed to be a directory, and target files will go within. Can submit a list of paths, which may be glob-patterns and will be expanded.

Calls get_file for each source.

glob(path, maxdepth=None, **kwargs)

Find files by glob-matching.

Pattern matching capabilities for finding files that match the given pattern.

Parameters:
  • path (str) – The glob pattern to match against

  • maxdepth (int or None) – Maximum depth for '**' patterns. Applied on the first '**' found. Must be at least 1 if provided.

  • kwargs – Additional arguments passed to find (e.g., detail=True)

Return type:

List of matched paths, or dict of paths and their info if detail=True

Notes

Supported patterns: - ‘*’: Matches any sequence of characters within a single directory level - '**': Matches any number of directory levels (must be an entire path component) - ‘?’: Matches exactly one character - ‘[abc]’: Matches any character in the set - ‘[a-z]’: Matches any character in the range - ‘[!abc]’: Matches any character NOT in the set

Special behaviors: - If the path ends with ‘/’, only folders are returned - Consecutive ‘*’ characters are compressed into a single ‘*’ - Empty set ‘[]’ or negated empty negated set ‘[!]’ never match anything - Special characters in character classes are escaped properly

Limitations: - '**' must be a complete path component (e.g., 'a/**/b', not 'a**b') - No brace expansion (‘{a,b}.txt’) - No extended glob patterns (‘+(pattern)’, ‘!(pattern)’)

lexists(path, **kwargs)

If there is a file at the given path (including broken links)

listdir(path, detail=True, **kwargs)

Alias of AbstractFileSystem.ls.

makedir(path, create_parents=True, **kwargs)

Alias of AbstractFileSystem.mkdir.

move(path1, path2, **kwargs)

Alias of AbstractFileSystem.mv.

open(path, mode='rb', block_size=None, cache_options=None, compression=None, **kwargs)

Return a file-like object from the filesystem

The resultant instance must function correctly in a context with block.

Parameters:
  • path (str) – Target file

  • mode (str like 'rb', 'w') – See builtin open() Mode “x” (exclusive write) may be implemented by the backend. Even if it is, whether it is checked up front or on commit, and whether it is atomic is implementation-dependent.

  • block_size (int) – Some indication of buffering - this is a value in bytes

  • cache_options (dict, optional) – Extra arguments to pass through to the cache.

  • compression (string or None) – If given, open file using compression codec. Can either be a compression name (a key in fsspec.compression.compr) or “infer” to guess the compression from the filename suffix.

  • encoding (passed on to TextIOWrapper for text mode)

  • errors (passed on to TextIOWrapper for text mode)

  • newline (passed on to TextIOWrapper for text mode)

pipe(path, value=None, **kwargs)

Put value into path

(counterpart to cat)

Parameters:
  • path (string or dict(str, bytes)) – If a string, a single remote location to put value bytes; if a dict, a mapping of {path: bytesvalue}.

  • value (bytes, optional) – If using a single path, these are the bytes to put there. Ignored if path is a dict

put(lpath, rpath, recursive=False, callback=<fsspec.callbacks.NoOpCallback object>, maxdepth=None, **kwargs)

Copy file(s) from local.

Copies a specific file or tree of files (if recursive=True). If rpath ends with a “/”, it will be assumed to be a directory, and target files will go within.

Calls put_file for each source.

read_bytes(path, start=None, end=None, **kwargs)

Alias of AbstractFileSystem.cat_file.

rename(path1, path2, **kwargs)

Alias of AbstractFileSystem.mv.

sign(path, expiration=100, **kwargs)

Create a signed URL representing the given path

Some implementations allow temporary URLs to be generated, as a way of delegating credentials.

Parameters:
  • path (str) – The path on the filesystem

  • expiration (int) – Number of seconds to enable the URL for (if supported)

Returns:

URL – The signed URL

Return type:

str

:raises NotImplementedError : if method is not implemented for a filesystem:

stat(path, **kwargs)

Alias of AbstractFileSystem.info.

upload(lpath, rpath, recursive=False, **kwargs)

Alias of AbstractFileSystem.put.

write_bytes(path, value, **kwargs)

Alias of AbstractFileSystem.pipe_file.

class fsspec_rs.S3FileSystem(*args, **kwargs)[source]

Bases: FileSystem

S3 filesystem backed by the Rust S3Fs implementation.

The protocol is registered as "s3-rs" so it can coexist with the pure-Python s3fs.S3FileSystem which owns the "s3" protocol.

Credential resolution:
  1. Explicit keyword arguments (key, secret, endpoint_url, …)

  2. Values from fsspec.config.conf["s3"] (populated from FSSPEC_S3_* environment variables)

  3. AWS environment credentials, then the instance-metadata provider.

Key, secret and optional token are selected together from one source. client_options accepts connect_timeout and request_timeout in seconds, and max_retries. Typed writes always disable automatic retries.

protocol: str | tuple[str, ...] = ('s3-rs',)
unstrip_protocol(path)[source]

Reconstruct s3-rs://bucket/key from bucket/key.

ls(path: str, detail: bool = True, **kwargs)[source]

List objects at path.

This should include subdirectories and files at that location. The difference between a file and a directory must be clear when details are requested.

The specific keys, or perhaps a FileInfo class, or similar, is TBD, but must be consistent across implementations. Must include:

  • full path to the entry (without protocol)

  • size of the entry, in bytes. If the value cannot be determined, will be None.

  • type of entry, “file”, “directory” or other

Additional information may be present, appropriate to the file-system, e.g., generation, checksum, etc.

May use refresh=True|False to allow use of self._ls_from_cache to check for a saved listing and avoid calling the backend. This would be common where listing may be expensive.

Parameters:
  • path (str)

  • detail (bool) – if True, gives a list of dictionaries, where each is the same as the result of info(path). If False, gives a list of paths (str).

  • kwargs (may have additional backend-specific options, such as version) – information

Returns:

  • List of strings if detail is False, or list of directory information

  • dicts if detail is True.

info(path: str, **kwargs)[source]

Give details of entry at path

Returns a single dictionary, with exactly the same information as ls would with detail=True.

The default implementation calls ls and could be overridden by a shortcut. kwargs are passed on to `ls().

Some file systems might not be able to measure the file’s size, in which case, the returned dict will include 'size': None.

Returns:

  • dict with keys (name (full path in the FS), size (in bytes), type (file,)

  • directory, or something else) and other FS-specific keys.

mkdir(path: str, create_parents: bool = True, **kwargs)[source]

Create directory entry at path

For systems that don’t have true directories, may create an for this instance only and not touch the real filesystem

Parameters:
  • path (str) – location

  • create_parents (bool) – if True, this is equivalent to makedirs

  • kwargs – may be permissions, etc.

rmdir(path: str)[source]

Remove a directory, if empty

rm_file(path: str)[source]

Delete a file

rm(path, recursive: bool = False, maxdepth=None)[source]

Delete files or directories.

Parameters:
  • path (str or list of str) – Files or directories to delete.

  • recursive (bool) – If True, recursively delete directories and their contents.

  • maxdepth (int or None) – Depth to pass to walk for finding files to delete, if recursive. If None, there will be no limit and infinite recursion may be possible.

cp_file(path1: str, path2: str, **kwargs)[source]
exists(path: str, **kwargs) → bool[source]

Is there a file at the given path

isdir(path: str) → bool[source]

Is this entry directory-like?

isfile(path: str) → bool[source]

Is this entry file-like?

size(path: str) → int[source]

Size in bytes of file

read(path: str, start=None, end=None, condition: Match | Missing | None = None) → ReadResult[source]
write(path: str, data: bytes, condition: Match | Missing | None = None) → WriteResult[source]
read_ranges(path: str, ranges: Sequence[tuple[int | None, int | None]], *, condition: Match | Missing | None = None, max_gap: int = 65536, max_request_size: int = 8388608, max_concurrency: int = 8) → RangeReadResult[source]
cat_ranges(paths, starts, ends, max_gap=None, on_error='return', **kwargs)[source]

Get the contents of byte ranges from one or more files

Parameters:
  • paths (list) – A list of of filepaths on this filesystems

  • starts (int or list) – Bytes limits of the read. If using a single int, the same value will be used to read all the specified files.

  • ends (int or list) – Bytes limits of the read. If using a single int, the same value will be used to read all the specified files.

io_capabilities() → IoCapabilities[source]
cat_file(path: str, start=None, end=None, condition: Match | Missing | None = None, **kwargs) → bytes[source]

Get the content of a file

Parameters:
  • path (URL of file on this filesystems)

  • start (int) – Bytes limits of the read. If negative, backwards from end, like usual python slices. Either can be None for start or end of file, respectively

  • end (int) – Bytes limits of the read. If negative, backwards from end, like usual python slices. Either can be None for start or end of file, respectively

  • kwargs (passed to open().)

pipe_file(path: str, value: bytes, condition: Match | Missing | None = None, **kwargs)[source]

Set the bytes of given file

head(path: str, size: int = 1024) → bytes[source]

Get the first size bytes from file

tail(path: str, size: int = 1024) → bytes[source]

Get the last size bytes from file

walk(path: str, maxdepth=None, topdown: bool = True, **kwargs)[source]

Return all files under the given path.

List all files, recursing into subdirectories; output is iterator-style, like os.walk(). For a simple list of files, find() is available.

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False has no effect. (see os.walk)

Note that the “files” outputted will include anything that is not a directory, such as links.

Parameters:
  • path (str) – Root to recurse into

  • maxdepth (int) – Maximum recursion depth. None means limitless, but not recommended on link-based file-systems.

  • topdown (bool (True)) – Whether to walk the directory tree from the top downwards or from the bottom upwards.

  • on_error ("omit", "raise", a callable) – if omit (default), path with exception will simply be empty; If raise, an underlying exception will be raised; if callable, it will be called with a single OSError instance as argument

  • kwargs (passed to ls)

find(path: str, maxdepth=None, withdirs: bool = False, **kwargs)[source]

List all files below path.

Like posix find command without conditions

Parameters:
  • path (str)

  • maxdepth (int or None) – If not None, the maximum number of levels to descend

  • withdirs (bool) – Whether to include directory paths in the output. This is True when used by glob, but users usually only want files.

  • ls. (kwargs are passed to)

read_text(path: str, encoding=None, errors=None, newline=None, **kwargs) → str[source]

Get the contents of the file as a string.

Parameters:
  • path (str) – URL of file on this filesystems

  • encoding (same as open.)

  • errors (same as open.)

  • newline (same as open.)

cat(path, recursive=False, on_error='raise', **kwargs)

Fetch (potentially multiple) paths’ contents

Parameters:
  • recursive (bool) – If True, assume the path(s) are directories, and get all the contained files

  • on_error ("raise", "omit", "return") – If raise, an underlying exception will be raised (converted to KeyError if the type is in self.missing_exceptions); if omit, keys with exception will simply not be included in the output; if “return”, all keys are included in the output, but the value will be bytes or an exception instance.

  • kwargs (passed to cat_file)

Returns:

  • dict of {path (contents} if there are multiple paths)

  • or the path has been otherwise expanded

copy(path1, path2, recursive=False, maxdepth=None, on_error=None, **kwargs)

Copy within two locations in the filesystem

on_error“raise”, “ignore”

If raise, any not-found exceptions will be raised; if ignore any not-found exceptions will cause the path to be skipped; defaults to raise unless recursive is true, where the default is ignore

cp(path1, path2, **kwargs)

Alias of AbstractFileSystem.copy.

disk_usage(path, total=True, maxdepth=None, **kwargs)

Alias of AbstractFileSystem.du.

download(rpath, lpath, recursive=False, **kwargs)

Alias of AbstractFileSystem.get.

du(path, total=True, maxdepth=None, withdirs=False, **kwargs)

Space used by files and optionally directories within a path

Directory size does not include the size of its contents.

Parameters:
  • path (str)

  • total (bool) – Whether to sum all the file sizes

  • maxdepth (int or None) – Maximum number of directory levels to descend, None for unlimited.

  • withdirs (bool) – Whether to include directory paths in the output.

  • kwargs (passed to find)

Returns:

  • Dict of {path (size} if total=False, or int otherwise, where numbers)

  • refer to bytes used.

expand_path(path, recursive=False, maxdepth=None, assume_literal=False, **kwargs)

Turn one or more globs or directories into a list of all matching paths to files or directories.

kwargs are passed to glob or find, which may in turn call ls

get(rpath, lpath, recursive=False, callback=<fsspec.callbacks.NoOpCallback object>, maxdepth=None, **kwargs)

Copy file(s) to local.

Copies a specific file or tree of files (if recursive=True). If lpath ends with a “/”, it will be assumed to be a directory, and target files will go within. Can submit a list of paths, which may be glob-patterns and will be expanded.

Calls get_file for each source.

get_file(rpath, lpath=None, callback=<fsspec.callbacks.NoOpCallback object>, outfile=None, **kwargs)

Copy single remote file to local

glob(path, maxdepth=None, **kwargs)

Find files by glob-matching.

Pattern matching capabilities for finding files that match the given pattern.

Parameters:
  • path (str) – The glob pattern to match against

  • maxdepth (int or None) – Maximum depth for '**' patterns. Applied on the first '**' found. Must be at least 1 if provided.

  • kwargs – Additional arguments passed to find (e.g., detail=True)

Return type:

List of matched paths, or dict of paths and their info if detail=True

Notes

Supported patterns: - ‘*’: Matches any sequence of characters within a single directory level - '**': Matches any number of directory levels (must be an entire path component) - ‘?’: Matches exactly one character - ‘[abc]’: Matches any character in the set - ‘[a-z]’: Matches any character in the range - ‘[!abc]’: Matches any character NOT in the set

Special behaviors: - If the path ends with ‘/’, only folders are returned - Consecutive ‘*’ characters are compressed into a single ‘*’ - Empty set ‘[]’ or negated empty negated set ‘[!]’ never match anything - Special characters in character classes are escaped properly

Limitations: - '**' must be a complete path component (e.g., 'a/**/b', not 'a**b') - No brace expansion (‘{a,b}.txt’) - No extended glob patterns (‘+(pattern)’, ‘!(pattern)’)

lexists(path, **kwargs)

If there is a file at the given path (including broken links)

listdir(path, detail=True, **kwargs)

Alias of AbstractFileSystem.ls.

makedir(path, create_parents=True, **kwargs)

Alias of AbstractFileSystem.mkdir.

move(path1, path2, **kwargs)

Alias of AbstractFileSystem.mv.

mv(path1, path2, recursive=False, maxdepth=None, **kwargs)

Move file(s) from one location to another

open(path, mode='rb', block_size=None, cache_options=None, compression=None, **kwargs)

Return a file-like object from the filesystem

The resultant instance must function correctly in a context with block.

Parameters:
  • path (str) – Target file

  • mode (str like 'rb', 'w') – See builtin open() Mode “x” (exclusive write) may be implemented by the backend. Even if it is, whether it is checked up front or on commit, and whether it is atomic is implementation-dependent.

  • block_size (int) – Some indication of buffering - this is a value in bytes

  • cache_options (dict, optional) – Extra arguments to pass through to the cache.

  • compression (string or None) – If given, open file using compression codec. Can either be a compression name (a key in fsspec.compression.compr) or “infer” to guess the compression from the filename suffix.

  • encoding (passed on to TextIOWrapper for text mode)

  • errors (passed on to TextIOWrapper for text mode)

  • newline (passed on to TextIOWrapper for text mode)

pipe(path, value=None, **kwargs)

Put value into path

(counterpart to cat)

Parameters:
  • path (string or dict(str, bytes)) – If a string, a single remote location to put value bytes; if a dict, a mapping of {path: bytesvalue}.

  • value (bytes, optional) – If using a single path, these are the bytes to put there. Ignored if path is a dict

put(lpath, rpath, recursive=False, callback=<fsspec.callbacks.NoOpCallback object>, maxdepth=None, **kwargs)

Copy file(s) from local.

Copies a specific file or tree of files (if recursive=True). If rpath ends with a “/”, it will be assumed to be a directory, and target files will go within.

Calls put_file for each source.

put_file(lpath, rpath, callback=<fsspec.callbacks.NoOpCallback object>, mode='overwrite', **kwargs)

Copy single file to remote

read_bytes(path, start=None, end=None, **kwargs)

Alias of AbstractFileSystem.cat_file.

rename(path1, path2, **kwargs)

Alias of AbstractFileSystem.mv.

sign(path, expiration=100, **kwargs)

Create a signed URL representing the given path

Some implementations allow temporary URLs to be generated, as a way of delegating credentials.

Parameters:
  • path (str) – The path on the filesystem

  • expiration (int) – Number of seconds to enable the URL for (if supported)

Returns:

URL – The signed URL

Return type:

str

:raises NotImplementedError : if method is not implemented for a filesystem:

stat(path, **kwargs)

Alias of AbstractFileSystem.info.

touch(path, truncate=True, **kwargs)

Create empty file, or update timestamp

Parameters:
  • path (str) – file location

  • truncate (bool) – If True, always set file size to 0; if False, update timestamp and leave file unchanged, if backend allows this

upload(lpath, rpath, recursive=False, **kwargs)

Alias of AbstractFileSystem.put.

write_bytes(path, value, **kwargs)

Alias of AbstractFileSystem.pipe_file.

write_text(path, value, encoding=None, errors=None, newline=None, **kwargs)

Write the text to the given file.

An existing file will be overwritten.

Parameters:
  • path (str) – URL of file on this filesystems

  • value (str) – Text to write.

  • encoding (same as open.)

  • errors (same as open.)

  • newline (same as open.)

S3 configuration

S3FileSystem and RustS3Fs accept client_options, a dictionary with connect_timeout and request_timeout in finite positive seconds, and max_retries as a nonnegative integer. Unknown keys and invalid values are rejected. Omitted settings retain the backend defaults: 5 seconds to connect, 30 seconds per request, and 10 retries. Typed writes always use zero retries; the setting applies to the general client used by reads and legacy operations. Request timeout is not an overall operation deadline.

For S3FileSystem, explicit credentials take precedence over fsspec.config.conf["s3"], then AWS environment credentials. Each source supplies key, secret and optional token together; partial explicit credentials are errors. RustS3Fs uses explicit credentials or AWS environment values directly. anon=True ignores credentials. Region precedence is explicit, Python fsspec configuration where applicable, AWS_REGION, then AWS_DEFAULT_REGION. Custom endpoints are explicit; AWS endpoint environment variables are ignored. Profiles, SSO and credential_process are not supported.

Instance caches retain construction-time environment defaults. Explicit endpoint, credentials and client options distinguish configured instances. To select a new credential context in Python, pass the new credentials explicitly; bypassing fsspec’s Python cache with skip_instance_cache=True also creates a new native S3 client. S3FileSystem and RustS3Fs use the built-in S3 constructor, bypassing protocol overrides and the shared C registry cache. General url_to_fs calls continue to use that registry.

S3 object-store adapter

fsspec_rs.obspec.S3ObjectStore(fs, *, prefix="") provides the synchronous Head, GetRange and GetRanges protocols from obspec 0.1.0. It requires a fsspec_rs.S3FileSystem and shares that filesystem’s native S3 client, credentials, runtime and range-request concurrency limit. It retains its own handle, so it remains usable after the filesystem is dropped. Construction performs no I/O. The adapter is included in both direct builds and wheels linked to libfsspec; obspec is not a runtime dependency.

from fsspec_rs import S3FileSystem
from fsspec_rs.obspec import S3ObjectStore

fs = S3FileSystem(bucket="measurements", region="us-east-1")
store = S3ObjectStore(fs, prefix="daily")
meta = store.head("data.parquet")
footer = store.get_range("data.parquet", start=meta["size"] - 8, length=8)
buffers = store.get_ranges("data.parquet", starts=[0, 4], ends=[4, 12])

Keys are nonempty paths relative to the bucket or optional prefix. URLs, leading or trailing slashes, empty segments, . and .. segments, backslashes and control characters are rejected. A bucket name inside a key is literal. Spaces, Unicode and percent signs are literal object-key characters; the adapter does not decode URL escapes. The filesystem currently escapes some characters in its logical paths before storage, while this native view uses the stored S3 key directly. Prefix follows the same rules, but may be empty.

Method

Result

head(path)

Metadata dictionary: path, size, UTC last_modified datetime, e_tag, version

get_range(path, *, start, end=None, length=None)

bytes for one range

get_ranges(path, *, starts, ends=None, lengths=None)

List of bytes, in input order including duplicates

Metadata uses native HEAD and never infers directories. path is relative to the adapter’s prefix; ETag and version are strings or None. Datetimes have Python’s microsecond precision. Modification times before the Unix epoch are unsupported and raise NotSupportedError. Each metadata call makes a fresh request. Filesystem fs.head(path) retains its existing meaning: read the first bytes of a file.

Ranges require exactly one of end/length (or ends/lengths), nonnegative integer bounds through 2**63 - 1, equal vector lengths, and a nonempty interval. Boolean bounds are rejected; integer-like bounds implementing __index__ are accepted. Starts at or past EOF fail; ends past EOF are clipped. Empty vectors return [] without I/O. Reads use the native coalescing defaults and require an ETag; every GET is checked against the metadata request’s validator. No cached metadata, async methods, streaming, listing or writes are exposed.

Exceptions named NotFoundError, PermissionDeniedError, PreconditionError, NotSupportedError and InvalidPathError support obspec.exceptions.map_exception. Native errors retain .kind and .retry_safe, with the original exception as their cause when mapped. Invalid range arguments raise ValueError or TypeError; other backend errors retain the normal operation error contract. Range request sizes and concurrency are bounded, but the returned buffers occupy memory proportional to the requested output.

Object I/O and conditions

Local, memory and S3 filesystems expose read(path, start=None, end=None, condition=None), write(path, data, condition=None) and io_capabilities(). read returns a frozen ReadResult with .data and .validator; write returns a frozen WriteResult with the committed object’s .validator. A backend without validators returns None.

from fsspec_rs import ConflictError, Match, Missing

created = fs.write("manifest.json", b"first", condition=Missing())
current = fs.read("manifest.json")
if current.validator is not None:
    try:
        updated = fs.write("manifest.json", b"next", condition=Match(current.validator))
    except ConflictError:
        # Another writer changed or deleted the object. Read again before retrying.
        pass

Match requires a Validator obtained from the same object’s read or write result. Validators are opaque equality tokens; retain both .scope and .value unchanged. S3 supports Match for reads and writes. Local and memory support Missing writes but do not provide validators or Match operations.

cat_file(..., condition=...) and pipe_file(..., condition=...) accept the same conditions and keep their existing return values. Use read and write to obtain validators. Missing is valid only for writes. Unknown condition types raise TypeError; invalid conditions or validator scope raise ValueError; unsupported conditions raise NotImplementedError. Conflicts raise ConflictError, an OSError subclass. Other filesystem errors keep their usual Python exception types. Passing condition= to open handles is unsupported.

See Rust object I/O for capability flags, range consistency and local exclusive-creation semantics.

Operation errors

Errors returned by typed read, write and read_ranges expose .kind and .retry_safe. The kind is one of not_found, already_exists, conflict, gap, permission_denied, unavailable, timeout, corrupt, invalid, cancelled, unknown_outcome, or the compatibility categories not_a_directory, is_a_directory, io, not_supported and other.

Standard Python exceptions remain available: FileNotFoundError, FileExistsError, PermissionError, TimeoutError, ValueError and NotImplementedError. Additional OSError subclasses are ConflictError, GapError, UnavailableError, CorruptError, CancelledError and UnknownOutcomeError. GapError is available for backends with positioned writes; byte writes do not produce it themselves. Argument errors raised before backend dispatch do not necessarily have operation metadata.

retry_safe=True means repeating the operation is safe. False includes cases where safety cannot be established. Transient S3 read failures are safe to retry; an uncertain write is not. Legacy file-handle operations retain their existing error contract.

Uncertain creates

S3 typed writes send one PUT attempt. Following an uncertain response to write(..., condition=Missing()), the backend reads the object and compares its SHA-256 checksum with the supplied bytes. Matching content acknowledges success; different content returns ConflictError. An absent object or failed verification returns UnknownOutcomeError with retry_safe=False. Local exclusive writes use the same content check after an I/O failure. An ETag is never treated as a content checksum.

Recovered success acknowledges matching content for immutable publication; it does not establish ownership of a lock or prove which writer created the object. A definitive precondition failure remains a conflict, including when existing content matches. Ordinary overwrites and Match writes with uncertain outcomes return UnknownOutcomeError without content-based recovery.

File write lifecycle

Native Python handles and the filesystem wrappers publish buffered writes on explicit close() or clean context-manager exit. discard() closes the handle without publishing pending data. Exceptional exits and finalizers discard. Uncompressed text handles returned by fs.open follow the same rules.

Direct local append writes are immediately visible and cannot be rolled back. Explicit flushes can pass text to the underlying handle. External wrappers, including compression and fsspec.open’s OpenFile, control their own close behavior; their exception handling is outside this lifecycle contract.

S3 exclusive handles still buffer the complete object. Ordinary S3 writers use multipart uploads for large objects; abandoned uploads are aborted on a best-effort basis. A process crash can leave multipart uploads requiring the store’s retention policy.

Range reads

read_ranges(path, ranges, *, condition=None, max_gap=65536, max_request_size=8388608, max_concurrency=8) returns a frozen RangeReadResult. Its .data is a tuple of bytes in requested order; .validator identifies the shared S3 object version or is None when unavailable. ranges contains (start, end) pairs with signed integers or None, as for read bounds.

result = fs.read_ranges("events.parquet", [(0, 16), (32, 48), (-8, None)])
first, second, footer = result.data

Nearby ranges are merged and oversized requests split. S3 fetches merged ranges concurrently against one validator. Local and memory use sequential reads without a snapshot guarantee. Match is supported by S3; Missing is invalid. Conditions and errors follow the typed read API. A failed operation returns no partial result.

cat_ranges(paths, starts, ends, max_gap=None, on_error="return", *, condition=None, max_request_size=8388608, max_concurrency=8) adapts fsspec’s list interface. paths is a list; scalar start/end bounds broadcast to its length. List lengths must match. Requests for the same normalized path are grouped and coalesced, then restored to input order. Different path groups execute sequentially. A condition cannot span multiple unique paths. An empty path list returns an empty list without I/O. max_gap=None selects the 65,536-byte default.

With on_error="return", a failed path group places its exception at each of that group’s output positions; "raise" propagates the error. Invalid argument shapes, options and condition types raise before I/O. Unknown keyword arguments are rejected. Use read_ranges to retain the validator with the bytes.

Compatibility with the inherited fsspec implementation:

  • cat_ranges is an existing fsspec API; read_ranges is the typed single-object batch API added by fsspec-rs.

  • Errors apply to a normalized path group. If a later request fails, previously fetched bytes for that path are discarded. With on_error="return", other path groups still run. The inherited implementation handled each range independently.

  • All offsets are validated before any path is read. Invalid offsets raise even with on_error="return".

  • S3 batches issue a metadata request and require an ETag when fetching bytes, even without condition. A missing ETag produces NotImplementedError; an object changed between requests can produce ConflictError. These errors follow on_error. Individual unconditional cat_file reads do not require an ETag or check consistency across calls.

See the Rust reference for shared endpoint concurrency limits, empty range behavior and memory bounds.

Open files

class fsspec_rs.LocalFile(fs: LocalFileSystem, path: str, mode: str = 'rb', cache_type=None, block_size=None, **kwargs)[source]

Bases: AbstractBufferedFile

File-like wrapper delegating to the Rust RustLocalFile.

read(length: int = -1) → bytes[source]

Return data from cache, or fetch pieces as necessary

Parameters:

length (int (-1)) – Number of bytes to read; if <0, all remaining bytes.

write(data: bytes) → int[source]

Write data to buffer.

Buffer only sent on flush() or if buffer is greater than or equal to blocksize.

Parameters:

data (bytes) – Set of bytes to be written.

seek(loc: int, whence: int = 0) → int[source]

Set current file location

Parameters:
  • loc (int) – byte location

  • whence ({0, 1, 2}) – from start of file, current location or end of file, resp.

tell() → int[source]

Current file location

flush(force: bool = False)[source]

Write buffered data to backend store.

Writes the current buffer, if it is larger than the block-size, or if the file is being closed.

Parameters:

force (bool) – When closing, write the last block even if it is smaller than blocks are allowed to be. Disallows further writing to this file.

close()[source]

Close file

Finalizes writes, discards cache

discard()[source]

Discard pending writes and close; direct local writes cannot be undone.

property closed: bool
readable() → bool[source]

Whether opened for reading

writable() → bool[source]

Whether opened for writing

seekable() → bool[source]

Whether is seekable (only in read mode)

class fsspec_rs.S3File(fs: S3FileSystem, path: str, mode: str = 'rb', cache_type=None, block_size=None, **kwargs)[source]

Bases: AbstractBufferedFile

File-like wrapper delegating to the Rust RustS3File.

read(length: int = -1) → bytes[source]

Return data from cache, or fetch pieces as necessary

Parameters:

length (int (-1)) – Number of bytes to read; if <0, all remaining bytes.

write(data: bytes) → int[source]

Write data to buffer.

Buffer only sent on flush() or if buffer is greater than or equal to blocksize.

Parameters:

data (bytes) – Set of bytes to be written.

seek(loc: int, whence: int = 0) → int[source]

Set current file location

Parameters:
  • loc (int) – byte location

  • whence ({0, 1, 2}) – from start of file, current location or end of file, resp.

tell() → int[source]

Current file location

flush(force: bool = False)[source]

Write buffered data to backend store.

Writes the current buffer, if it is larger than the block-size, or if the file is being closed.

Parameters:

force (bool) – When closing, write the last block even if it is smaller than blocks are allowed to be. Disallows further writing to this file.

close()[source]

Close file

Finalizes writes, discards cache

discard()[source]

Discard pending writes and close; direct local writes cannot be undone.

property closed: bool
readable() → bool[source]

Whether opened for reading

writable() → bool[source]

Whether opened for writing

seekable() → bool[source]

Whether is seekable (only in read mode)

Metadata types

class fsspec_rs.FileInfo(name, size=0, file_type=None)

Bases: object

Python-visible file metadata, analogous to the dict returned by fsspec’s info().

file_type

The file type as a string (“file”, “directory”, “other”).

is_dir()

Whether this is a directory.

is_file()

Whether this is a regular file.

name

The full path name.

size

Size in bytes.

to_dict()

Convert to a Python dict matching fsspec’s info() format.

class fsspec_rs.FileType

Bases: object

Python-visible enum for file types.

as_str()

Return the string representation used by fsspec (“file”, “directory”, “other”).

static directory()

Create a FileType representing a directory.

static file()

Create a FileType representing a regular file.

static other()

Create a FileType representing an other entry.