文件系统
更新时间 2026-05-11 16:21:07
最近更新时间: 2026-05-11 16:21:07
前提条件
在控制台完成沙箱模板创建。
在执行下文所有代码前,请先按照环境变量设置部分,完成环境变量设置。
文件读取与下载
从沙箱实例中读取文件内容,或下载文件到本地。
from e2b_code_interpreter import Sandbox
# 注意:修改下面模板为您的模板名称或者模板id
sandbox = Sandbox.create(template="my_test_code_template")
# 从沙箱实例中读取文件
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 方法向沙箱实例中写入文件。
from e2b_code_interpreter import Sandbox
# 注意:修改下面模板为您的模板名称或者模板id
sandbox = Sandbox.create(template="my_test_code_template")
# 向沙箱实例中写入单个文件
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 方法来检测沙箱实例中是否存在某个文件。
response = sandbox.files.exists("file_name")
# 存在 True
# 不存在 False重命名文件
您可以使用 files 类的 rename 方法来重命名沙箱实例中的某个文件。
response = sandbox.files.rename("file_name_before","file_name_after")创建文件夹
您可以使用 files 类的 make_dir 方法来在沙箱实例中创建文件夹。
response = sandbox.files.make_dir("dir_name")监控文件变化
您可以使用 files 类的 watch_dir 方法来创建一个文件监控器 watch_handle 类。
通过 watch_handle 类的 get_new_events 方法可以获得这段时间的文件变更事件。
# 创建一个文件监控器
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()