文件系统

最近更新时间:2025-09-28 18:50:42

我的收藏

前提条件

在执行下文所有代码前,请先按照 配置环境变量 部分完成环境变量设置。
若您使用 e2b_code_interpreter sdk 且不指定 template,必须已在账号下创建名为 code-interpreter-v1 的代码解释器沙箱工具。

文件读取下载

从沙箱实例中读取文件内容,或下载文件到本地。
Python
from e2b_code_interpreter import Sandbox
# 创建沙箱实例
sandbox = Sandbox.create()
# 从沙箱实例中读取文件
file_content = sandbox.files.read("your-file-path")
# 从沙箱实例中下载文件到本地
with open("local-path","wb") as file:
# 以二进制形式读取文件
file.write(sandbox.files.read("your-file-path","bytes"))

文件写入与上传

您可以使用 files 类的 write 和 write_files 方法向沙箱实例中写入文件。
Python
from e2b_code_interpreter import Sandbox
# 创建沙箱实例
sandbox = Sandbox.create()
# 向沙箱实例中写入单个文件
sandbox.files.write("your-file-path","file-content")
# 向沙箱实例中上传文件
with open("local-path","rb") as file:
# 以二进制形式上传文件
sandbox.files.write("your-file-path",file)
# 向沙箱实例中写入多个文件
sandbox.files.write_files(
[
{"path": "your-path-1", "data": "file-content"},
{"path": "your-path-2", "data": "file-content"},
]
)

检查文件是否存在

您可以使用 files 类的 exists 方法来检测沙箱实例中是否存在某个文件。
Python
response = sandbox.files.exists("file_name")
# 存在 True
# 不存在 False

重命名文件

您可以使用 files 类的 rename 方法来重命名沙箱实例中的某个文件。
Python
response = sandbox.files.rename("file_name_before","file_name_after")

创建文件夹

您可以使用 files 类的 make_dir 方法来在沙箱实例中创建文件夹。
Python
response = sandbox.files.make_dir("dir_name")

监控文件变化

您可以使用 files 类的 watch_dir 方法来创建一个文件监控器 watch_handle 类。
通过 watch_handle 类的 get_new_events 方法可以获得这段时间的文件变更事件。
Python
# 创建一个文件监控器
watch_handle = sandbox.files.watch_dir(".")
# 创建一个tempfile.txt并写入内容
sandbox.files.write("tempfile.txt","temp file")
# 删除tempfile.txt
sandbox.files.remove("tempfile.txt")
# 打印这段时间的所有事件
for event in watch_handle.get_new_events():
print(event)
# 事件示例
# FilesystemEvent(name='tempfile.txt', type=<FilesystemEventType.CREATE: 'create'>)
# FilesystemEvent(name='tempfile.txt', type=<FilesystemEventType.CHMOD: 'chmod'>)
# FilesystemEvent(name='tempfile.txt', type=<FilesystemEventType.WRITE: 'write'>)
# FilesystemEvent(name='tempfile.txt', type=<FilesystemEventType.REMOVE: 'remove'>)
# 停止文件监控器
watch_handle.stop()