Skip to main content
Use sandbox.files.read() to read file contents. Supports text, binary, and streaming modes.

Read as Text

The default format returns file contents as a string:
from moru import Sandbox

sandbox = Sandbox.create()

# Read as text (default)
content = sandbox.files.read("/etc/hostname")
print(content)

# Explicitly specify text format
content = sandbox.files.read("/home/user/script.py", format="text")

Read as Bytes

For binary files, read as bytes:
# Read as bytes
data = sandbox.files.read("/path/to/image.png", format="bytes")
print(f"File size: {len(data)} bytes")

# Save locally
with open("local_copy.png", "wb") as f:
    f.write(data)

Stream Large Files

For large files, use streaming to avoid loading everything into memory:
# Read as stream (iterator)
stream = sandbox.files.read("/path/to/large_file.bin", format="stream")

with open("local_copy.bin", "wb") as f:
    for chunk in stream:
        f.write(chunk)

Read with User Context

Read files as a specific user:
# Read as root
content = sandbox.files.read("/etc/shadow", user="root")

# Read as another user
content = sandbox.files.read("/home/alice/private.txt", user="alice")

Error Handling

Handle common read errors:
from moru import Sandbox
from moru.exceptions import NotFoundException

try:
    content = sandbox.files.read("/nonexistent/file.txt")
except NotFoundException:
    print("File not found")
except Exception as e:
    print(f"Read failed: {e}")

Reading Multiple Files

Read multiple files efficiently:
# Read multiple files
files_to_read = [
    "/home/user/config.json",
    "/home/user/data.csv",
    "/home/user/readme.txt"
]

contents = {}
for path in files_to_read:
    if sandbox.files.exists(path):
        contents[path] = sandbox.files.read(path)

Download URL

Get a URL to download files directly:
# Get download URL (valid for limited time)
url = sandbox.download_url("/path/to/file.zip")
print(f"Download from: {url}")

Options Reference

OptionTypeDescription
format"text" | "bytes" | "stream" | "blob" (JS)Output format
userstringUser context for reading
request_timeout / requestTimeoutMsnumberOperation timeout

Next Steps