全部产品
Search
文档中心

函数计算:读写文件

更新时间:Sep 18, 2026

Filesystem 用于管理 Sandbox 内的文件。常见流程是先写入输入文件或代码,再执行命令,最后读取结果文件。

写入并读取文件

Python 示例:

import os

from e2b import Sandbox

sandbox = Sandbox.create(
    template="code-interpreter-v1",
    api_key=os.environ["E2B_API_KEY"],
    api_url=os.environ["E2B_API_URL"],
    domain=os.environ["E2B_DOMAIN"],
)

try:
    sandbox.files.write("/tmp/hello.txt", "hello from fc sandbox\n")
    content = sandbox.files.read("/tmp/hello.txt")
    print(content.strip())
finally:
    sandbox.kill()

TypeScript 示例:

import { Sandbox } from "e2b";

const sandbox = await Sandbox.create("code-interpreter-v1", {
  apiKey: process.env.E2B_API_KEY,
  apiUrl: process.env.E2B_API_URL,
  domain: process.env.E2B_DOMAIN,
});

try {
  await sandbox.files.write("/tmp/hello.txt", "hello from fc sandbox\n");
  const content = await sandbox.files.read("/tmp/hello.txt");
  console.log(content.trim());
} finally {
  await sandbox.kill();
}

批量写入文件

TypeScript SDK 支持一次写入多个文件,适合把 Agent 生成的代码、测试文件和配置文件一起放入 Sandbox。

Python 示例:

sandbox.files.make_dir("/tmp/project")

sandbox.files.write("/tmp/project/main.py", "print('hello')\n")
sandbox.files.write("/tmp/project/README.md", "# Demo\n")

TypeScript 示例:

await sandbox.files.makeDir("/tmp/project");

await sandbox.files.write([
  {
    path: "/tmp/project/main.py",
    data: "print('hello')\n",
  },
  {
    path: "/tmp/project/README.md",
    data: "# Demo\n",
  },
]);

write() 写入已存在文件时会覆盖原文件;写入不存在的路径时,会自动创建缺失的父目录。除文本外,Python SDK 支持写入 bytes 和文件对象,TypeScript SDK 支持写入 ArrayBufferBlobReadableStream。读取文件时,read() 默认返回文本,也可以读取为字节或流。

Python 示例:

sandbox.files.write("/tmp/data.bin", bytes([1, 2, 3]))

data = sandbox.files.read("/tmp/data.bin", format="bytes")
print(len(data))

TypeScript 示例:

await sandbox.files.write("/tmp/data.bin", new Uint8Array([1, 2, 3]).buffer);

const bytes = await sandbox.files.read("/tmp/data.bin", { format: "bytes" });
console.log(bytes.length);

支持的方法

  • sandbox.files.list():列出目录内容。

  • sandbox.files.exists():判断文件或目录是否存在。

  • sandbox.files.read():读取文件。

  • sandbox.files.write():写入文件。

  • sandbox.files.makeDir():创建目录。

  • sandbox.files.remove():删除文件或目录。

  • sandbox.files.rename():移动或重命名。

使用建议

  • 临时输入、生成代码和中间结果建议写入 /tmp 或业务自定义工作目录。

  • 需要跨 Sandbox 保留的数据,应使用外部存储或持久化方案,不要依赖 Sandbox 本地文件系统。

  • 写入用户上传文件前,建议在业务侧做文件类型、大小和路径校验。

  • 读写完成后,任务仍应主动调用 sandbox.kill() 释放 Sandbox。

后续阅读