Skip to main content

What You’ll Learn

  • Writing a file with sbx.files.write()
  • Reading a file with sbx.files.read()
  • Checking file existence with sbx.files.exists()
  • Getting file metadata with sbx.files.get_info() / sbx.files.getInfo()
  • Listing directory contents with sbx.files.list()
  • Creating directories with sbx.files.make_dir() / sbx.files.makeDir()
  • Renaming files with sbx.files.rename()
  • Batch writing with sbx.files.write_files() / sbx.files.writeFiles()
  • Removing files with sbx.files.remove()

Prerequisites

Code Walkthrough

Import WriteEntry for batch operations:
from declaw import Sandbox, WriteEntry
Write and read a file:
sbx.files.write("/tmp/hello.txt", "Hello, Declaw!")
content = sbx.files.read("/tmp/hello.txt")
print(f"Content: {content}")  # Hello, Declaw!
Check existence and get metadata:
exists = sbx.files.exists("/tmp/hello.txt")
print(f"Exists: {exists}")  # True

info = sbx.files.get_info("/tmp/hello.txt")
print(f"Name: {info.name}")   # hello.txt
print(f"Type: {info.type}")   # FileType.FILE
print(f"Size: {info.size}")   # 14
List directory:
entries = sbx.files.list("/tmp")
for entry in entries:
    print(f"  {entry.name} ({entry.type})")
Make a directory, rename a file:
sbx.files.make_dir("/tmp/mydir")
sbx.files.rename("/tmp/hello.txt", "/tmp/renamed.txt")
Batch write multiple files at once:
sbx.files.write_files([
    WriteEntry(path="/tmp/a.txt", data="aaa"),
    WriteEntry(path="/tmp/b.txt", data="bbb"),
])
Remove a file and verify:
sbx.files.remove("/tmp/renamed.txt")
exists = sbx.files.exists("/tmp/renamed.txt")
print(f"Exists: {exists}")  # False

Expected Output

==================================================
Declaw File Operations Example
==================================================

--- Creating Sandbox ---
Sandbox created: sbx_abc123

--- Section 1: Write File ---
Wrote /tmp/hello.txt

--- Section 2: Read File ---
Content: Hello, Declaw!

--- Section 3: Check Exists ---
Exists: True

--- Section 4: Get Info ---
Name: hello.txt
Type: FileType.FILE
Size: 14

--- Section 5: List Directory ---
  hello.txt (file)
  ...

--- Section 6: Make Directory ---
Created /tmp/mydir

--- Section 7: Rename File ---
Renamed /tmp/hello.txt -> /tmp/renamed.txt

--- Section 8: Batch Write ---
Batch wrote /tmp/a.txt and /tmp/b.txt

--- Section 9: Remove File ---
Removed /tmp/renamed.txt

--- Section 10: Verify Removed ---
Exists: False

--- Cleaning Up ---
Sandbox killed.

==================================================
Done!
==================================================