Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt

Use this file to discover all available pages before exploring further.

List directory contents to browse your sandbox filesystem. Get file metadata including size, permissions, and modification times.

Overview

Directory listing is useful for:
  • Browsing sandbox filesystem structure
  • Finding files by name or pattern
  • Checking file sizes and metadata
  • Discovering generated outputs
You can list contents of allowed paths like /workspace and /tmp. Listing system directories may be restricted for security.

Basic Listing

List files in a directory:
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Create some files
sandbox.files.write('/workspace/file1.txt', 'Content 1')
sandbox.files.write('/workspace/file2.txt', 'Content 2')
sandbox.files.mkdir('/workspace/subdir')

# List directory contents
files = sandbox.files.list('/workspace')
print(f"Found {len(files)} items")

for file in files:
    if file.is_file:
        print(f"📄 {file.name} ({file.size_kb:.2f} KB)")
    else:
        print(f"📁 {file.name}/")

sandbox.kill()

File Information

Access detailed file information:
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Create a file
sandbox.files.write('/workspace/data.txt', 'Some content')

# List and get file info
files = sandbox.files.list('/workspace')
for file in files:
    if file.name == 'data.txt':
        print(f"Name: {file.name}")
        print(f"Path: {file.path}")
        print(f"Size: {file.size} bytes")
        print(f"Size (KB): {file.size_kb:.2f} KB")
        print(f"Size (MB): {file.size_mb:.2f} MB")
        print(f"Is file: {file.is_file}")
        print(f"Is directory: {file.is_dir}")
        print(f"Permissions: {file.permissions}")
        print(f"Modified: {file.modified_time}")

sandbox.kill()

Filtering Files

Filter files by type or pattern:
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Create various files
sandbox.files.write('/workspace/script.py', 'print("Hello")')
sandbox.files.write('/workspace/data.json', '{"key": "value"}')
sandbox.files.write('/workspace/readme.txt', 'Documentation')

# List only Python files
files = sandbox.files.list('/workspace')
python_files = [f for f in files if f.is_file and f.name.endswith('.py')]
print(f"Python files: {len(python_files)}")
for f in python_files:
    print(f"  {f.name}")

# List only directories
directories = [f for f in files if f.is_dir]
print(f"\nDirectories: {len(directories)}")
for d in directories:
    print(f"  {d.name}/")

sandbox.kill()

Recursive Listing

List files recursively by traversing directories:
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Create nested structure
sandbox.files.mkdir('/workspace/project')
sandbox.files.mkdir('/workspace/project/src')
sandbox.files.write('/workspace/project/src/main.py', 'print("Hello")')
sandbox.files.write('/workspace/project/README.md', '# Project')

def list_recursive(files, path='/workspace', indent=0):
    """Recursively list directory contents"""
    items = sandbox.files.list(path)
    for item in items:
        prefix = "  " * indent
        if item.is_dir:
            print(f"{prefix}📁 {item.name}/")
            list_recursive(files, item.path, indent + 1)
        else:
            print(f"{prefix}📄 {item.name} ({item.size_kb:.2f} KB)")

print("Directory structure:")
list_recursive(sandbox.files.list('/workspace'))

sandbox.kill()

Sorting and Filtering

Sort files by size, name, or date:
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Create files of different sizes
sandbox.files.write('/workspace/small.txt', 'small')
sandbox.files.write('/workspace/medium.txt', 'x' * 1000)
sandbox.files.write('/workspace/large.txt', 'x' * 10000)

# List and sort by size
files = sandbox.files.list('/workspace')
files_only = [f for f in files if f.is_file]

# Sort by size (largest first)
sorted_by_size = sorted(files_only, key=lambda f: f.size, reverse=True)
print("Files sorted by size:")
for f in sorted_by_size:
    print(f"  {f.name}: {f.size_kb:.2f} KB")

# Sort by name
sorted_by_name = sorted(files_only, key=lambda f: f.name)
print("\nFiles sorted by name:")
for f in sorted_by_name:
    print(f"  {f.name}")

sandbox.kill()

Complete Example

Here’s a complete example showing directory listing:
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")

# Create a project structure
sandbox.files.mkdir('/workspace/myproject')
sandbox.files.mkdir('/workspace/myproject/src')
sandbox.files.mkdir('/workspace/myproject/tests')
sandbox.files.mkdir('/workspace/myproject/data')

# Create files
sandbox.files.write('/workspace/myproject/src/main.py', 'print("Hello")')
sandbox.files.write('/workspace/myproject/src/utils.py', 'def helper(): pass')
sandbox.files.write('/workspace/myproject/tests/test_main.py', 'def test(): pass')
sandbox.files.write('/workspace/myproject/data/input.csv', '1,2,3')
sandbox.files.write('/workspace/myproject/README.md', '# My Project')

# List and display structure
def display_tree(path, prefix=""):
    files = sandbox.files.list(path)
    files.sort(key=lambda f: (f.is_dir, f.name))
    
    for i, file in enumerate(files):
        is_last = i == len(files) - 1
        current_prefix = "└── " if is_last else "├── "
        print(f"{prefix}{current_prefix}{file.name}")
        
        if file.is_dir:
            next_prefix = prefix + ("    " if is_last else "│   ")
            display_tree(file.path, next_prefix)

print("Project structure:")
display_tree('/workspace/myproject')

# Summary
all_files = sandbox.files.list('/workspace/myproject')
total_size = sum(f.size for f in all_files if f.is_file)
print(f"\nTotal files: {len([f for f in all_files if f.is_file])}")
print(f"Total size: {total_size / 1024:.2f} KB")

sandbox.kill()

Best Practices

1

1. Check Directory Existence

Use files.exists() before listing to avoid errors, or handle FileNotFoundError appropriately.
2

2. Filter by Type

Use is_file and is_dir properties to filter files and directories.
3

3. Sort for Display

Sort files by name, size, or date for better user experience.
4

4. Use Recursive Listing

For nested structures, implement recursive listing to show complete directory trees.
5

5. Handle Large Directories

For directories with many files, consider pagination or filtering to avoid performance issues.

Next Steps