# 文件系统 API

`HfFileSystem` 类基于 [`fsspec`](https://filesystem-spec.readthedocs.io/en/latest/)，为 Hugging Face Hub 提供了一个符合 Python 风格的文件接口。

## HfFileSystem[[huggingface_hub.HfFileSystem]]

`HfFileSystem` 基于 [fsspec](https://filesystem-spec.readthedocs.io/en/latest/)，因此与其提供的大多数 API 兼容。更多详情，请参阅[我们的指南](../guides/hf_file_system)和 fsspec 的[API Reference](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem)。

#### huggingface_hub.HfFileSystem[[huggingface_hub.HfFileSystem]]

```python
huggingface_hub.HfFileSystem(*args, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L370)

**参数：**

endpoint (`str`, *可选*) : Hub 的端点。默认为 。

token (`bool` 或 `str`，*可选*)：有效的用户访问令牌（字符串）。默认使用本地保存的令牌，这是推荐的认证方式（参见 https://huggingface.co/docs/huggingface_hub/quick-start#authentication）。若要禁用认证，请传入 `False`。

block_size (`int`, *可选*) : 读写文件的块大小。

expand_info (`bool`, *可选*) : 是否展开文件的信息。

max_workers (`int`, *可选*) : 用于并行列出大型目录的最大并发请求数（参见 [find()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_file_system#huggingface_hub.HfFileSystem.find)）。默认值为 16。将其设置为 1 可禁用并行列出。

live_follow (`bool`, *可选*) : 是否实时跟踪 Hub 上桶（bucket）中的文件变更，以便缓存的列表保持最新，而无需手动调用 [HfFileSystem.invalidate_cache()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_file_system#huggingface_hub.HfFileSystem.invalidate_cache)。启用后，列出桶时会打开到该桶 Hub 事件流的后台连接。对模型、数据集和空间仓库无效（Hub 不为这些仓库提供变更事件流）。

- ****storage_options** (`dict`, *可选*) : 文件系统的附加选项。请参阅 [fsspec 文档](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.__init__)。

将远程 Hugging Face Hub 仓库作为本地文件系统访问。

> [!WARNING]
> [HfFileSystem](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_file_system#huggingface_hub.HfFileSystem) 提供了 fsspec 兼容性，这对于需要该兼容性的库非常有用（例如，直接使用 `pandas` 读取 Hugging Face 数据集）。然而，由于这一兼容层，它会引入额外的开销。为了获得更好的性能和可靠性，建议尽可能使用 `HfApi` 方法。

文件系统支持 `hf://` 协议的路径，该协议遵循以下 URL 方案：

* 模型、数据集和 Spaces 仓库：

```
hf://<repo-id>[@<revision>]/<path/in/repo>
hf://datasets/<repo-id>[@<revision>]/<path/in/repo>
hf://spaces/<repo-id>[@<revision>]/<path/in/repo>
```

* Buckets （通用存储）：

```
hf://buckets/<bucket-id>/<path/in/bucket>
```

注意：直接使用 [HfFileSystem](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_file_system#huggingface_hub.HfFileSystem) 时，路径中的 `hf://` 协议前缀是可选的。

用法：

```python
>>> from huggingface_hub import hffs

>>> # List files
>>> hffs.glob("my-username/my-model/*.bin")
['my-username/my-model/pytorch_model.bin']
>>> hffs.ls("datasets/my-username/my-dataset", detail=False)
['datasets/my-username/my-dataset/.gitattributes', 'datasets/my-username/my-dataset/README.md', 'datasets/my-username/my-dataset/data.json']

>>> # Read/write files
>>> with hffs.open("my-username/my-model/pytorch_model.bin") as f:
...     data = f.read()
>>> with hffs.open("my-username/my-model/pytorch_model.bin", "wb") as f:
...     f.write(data)
```

指定用于身份验证的令牌：
```python
>>> from huggingface_hub import HfFileSystem
>>> hffs = HfFileSystem(token=token)
```

#### cp_file[[huggingface_hub.HfFileSystem.cp_file]]

```python
cp_file(path1: str, path2: str, revision: str | None = None, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L1115)

**参数：**

path1 (`str`) : 要复制的源路径。

path2 (`str`) : 要复制到的目标路径。

revision (`str`, *可选*) : 要从中复制的 git 修订版本。

在仓库内部或仓库之间复制文件，或复制到存储桶中。

> [!WARNING]
> 注意：在可能的情况下，请使用 `HfApi.upload_file()` 以获得更好的性能。

#### exists[[huggingface_hub.HfFileSystem.exists]]

```python
exists(path, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L1336)

**参数：**

path (`str`) : 要检查的路径。

**返回：** `bool`

如果文件存在，则为 True，否则为 False。

检查文件是否存在。

有关更多详细信息，请参阅 [fsspec 文档](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.exists)。

> [!WARNING]
> 注意：在可能的情况下，请使用 `HfApi.file_exists()` 以获得更好的性能。

#### 查找[[huggingface_hub.HfFileSystem.find]]

```python
find(path: str, maxdepth: int | None = None, withdirs: bool = False, detail: bool = False, refresh: bool = False, revision: str | None = None, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L1051)

**参数：**

path (`str`) : 列出文件的根路径。

maxdepth (`int`, *可选*) : 进入子目录的最大深度。

withdirs (`bool`, *可选*) : 在输出中包含目录路径。默认为 False。

detail (`bool`, *可选*) : 如果为 True，则返回一个将路径映射到文件信息的字典。默认为 False。

refresh (`bool`, *可选*) : 如果为 True，则绕过缓存并获取最新数据。默认为 False。

revision (`str`, *可选*) : 要列出内容的 git 修订版本。

**返回：** `Union[list[str], dict[str, dict[str, Any]]]`

路径列表或文件信息字典。

列出路径下的所有文件。

有关更多详细信息，请参阅 [fsspec 文档](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.find)。

> [!TIP]
> 大型仓库会按目录并行列出，以绕过 Hub `tree` 端点的基于游标的分页。可通过 [HfFileSystem](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_file_system#huggingface_hub.HfFileSystem) 的 `max_workers` 参数进行调整。

#### get_file[[huggingface_hub.HfFileSystem.get_file]]

```python
get_file(rpath, lpath = None, callback = <fsspec.callbacks.NoOpCallback object at 0x7f9673955c90>, outfile = None, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L1444)

**参数：**

rpath (`str`) : 要下载的远程路径。

lpath (`str`, *可选*) : 下载到的本地路径。如果提供了 `outfile`，则可以省略。

callback (`Callback`, *可选*) : 用于跟踪下载进度的可选回调。默认无回调。

outfile (`IO`，*可选*)：要写入的可选文件类对象。如果提供，则忽略 `lpath`。

将单个远程文件复制到本地。

> [!WARNING]
> 注意：在可能的情况下，请使用 `HfApi.hf_hub_download()` 或 `HfApi.download_bucket_files` 以获得更好的性能。

#### glob[[huggingface_hub.HfFileSystem.glob]]

```python
glob(path: str, maxdepth: int | None = None, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L1033)

**参数：**

path (`str`) : 要匹配的路径模式。

maxdepth (`int`, *可选*) : 进入目录的最大深度。默认情况下，没有限制。

**返回：** `list[str]`

匹配该模式的路径列表。

通过 glob 匹配查找文件。

有关更多详细信息，请参阅 [fsspec 文档](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.glob)。

#### info[[huggingface_hub.HfFileSystem.info]]

```python
info(path: str, refresh: bool = False, revision: str | None = None, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L1226)

**参数：**

path (`str`) : 要获取信息的文件路径。

refresh (`bool`, *可选*) : 如果为 True，则绕过缓存并获取最新数据。默认为 False。

revision (`str`, *可选*) : 用于获取信息的 git 修订版本。

**返回：** `dict[str, Any]`

包含文件信息（类型、大小、提交信息等）的字典。

获取文件或目录的信息。

有关更多详细信息，请参阅 [fsspec 文档](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.info)。

> [!WARNING]
> 注意：在可能的情况下，使用 `HfApi.get_paths_info()` 或 `HfApi.repo_info()` 以获得更好的性能（对于存储桶，使用 `HfApi.get_bucket_paths_info()` 或 `HfApi.bucket_info()`）

#### invalidate_cache[[huggingface_hub.HfFileSystem.invalidate_cache]]

```python
invalidate_cache(path: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L599)

**参数：**

path (`str`, *可选*) : 要从缓存中清除的路径。如果未提供，则清除整个缓存。

清除指定路径的缓存。

有关更多详细信息，请参阅 [fsspec 文档](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.invalidate_cache)。

#### isdir[[huggingface_hub.HfFileSystem.isdir]]

```python
isdir(path)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L1361)

**参数：**

path (`str`) : 要检查的路径。

**返回：** `bool`

如果 path 是目录，则为 True，否则为 False。

检查路径是否为目录。

有关更多详细信息，请参阅 [fsspec 文档](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isdir)。

#### isfile[[huggingface_hub.HfFileSystem.isfile]]

```python
isfile(path)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L1379)

**参数：**

path (`str`) : 要检查的路径。

**返回：** `bool`

如果 path 是文件，则为 True，否则为 False。

检查路径是否为文件。

有关更多详细信息，请参阅 [fsspec 文档](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isfile)。

#### ls[[huggingface_hub.HfFileSystem.ls]]

```python
ls(path: str, detail: bool = True, refresh: bool = False, revision: str | None = None, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L788)

**参数：**

path (`str`) : 目录的路径。

detail (`bool`, *可选*) : 如果为 True，则返回包含文件信息的字典列表。如果为 False，则返回文件路径列表。默认为 True。

refresh (`bool`, *可选*) : 如果为 True，则绕过缓存并获取最新数据。默认为 False。

revision (`str`, *可选*) : 要列出内容的 git 修订版本。

**返回：** `list[Union[str, dict[str, Any]]]`

文件路径列表（如果 detail=False）或文件信息字典列表（如果 detail=True）。

列出目录的内容。

有关更多详细信息，请参阅 [fsspec 文档](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.ls)。

> [!WARNING]
> 注意：在可能的情况下，请使用 `HfApi.list_repo_tree()` 以获得更好的性能。

#### 已修改[[huggingface_hub.HfFileSystem.modified]]

```python
modified(path: str, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L1201)

**参数：**

path (`str`) : 文件路径。

**返回：** `datetime`

文件的最后修改时间。

获取文件的最后修改时间。

有关更多详细信息，请参阅 [fsspec 文档](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.modified)。

#### resolve_path[[huggingface_hub.HfFileSystem.resolve_path]]

```python
resolve_path(path: str, revision: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L520)

**参数：**

path (`str`) : 要解析的路径。

revision (`str`, *可选*) : 要解析的仓库版本。默认使用路径中指定的版本。

**返回：** `HfFileSystemResolvedPath`

包含 `repo_type`、`repo_id`、`revision` 和 `path_in_repo` 的已解析路径信息。

**引发：** ``ValueError`` 或 ``NotImplementedError``

- ``ValueError`` -- 如果 path 包含冲突的 revision 信息。
- ``NotImplementedError`` --  如果尝试列出仓库。

将 Hugging Face 文件系统路径解析为其各个组成部分。

#### rm[[huggingface_hub.HfFileSystem.rm]]

```python
rm(path: str, recursive: bool = False, maxdepth: int | None = None, revision: str | None = None, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L738)

**参数：**

path (`str`) : 要删除的路径。

recursive (`bool`, *可选*) : 如果为 True，则删除目录及其所有内容。默认为 False。

maxdepth (`int`, *可选*) : 递归删除时要访问的最大子目录数。

revision (`str`, *可选*) : 要从中删除的 git 修订版本。

从存储库中删除文件。

有关更多详细信息，请参阅 [fsspec 文档](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.rm)。

> [!WARNING]
> 注意：在可能的情况下，请使用 `HfApi.delete_file()` 以获得更好的性能。

#### url[[huggingface_hub.HfFileSystem.url]]

```python
url(path: str)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L1397)

**参数：**

path (`str`) : 要获取 URL 的路径。

**返回：** `str`

用于访问 Hub 上文件或目录的 HTTP URL。

获取给定路径的 HTTP URL。

#### walk[[huggingface_hub.HfFileSystem.walk]]

```python
walk(path: str, *args, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hf_file_system.py#L1017)

**参数：**

path (`str`) : 列出文件的根路径。

**返回：** `Iterator[tuple[str, list[str], list[str]]]`

(path、目录名称列表、文件名称列表) 元组的迭代器。

返回给定路径下的所有文件。

有关更多详细信息，请参阅 [fsspec 文档](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.walk)。

