全部產品
Search
文件中心

Function Compute:讀寫檔案

更新時間:Jul 22, 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 支援寫入 ArrayBuffer、Blob 和 ReadableStream。讀取檔案時,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。

後續閱讀