> ## 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.

# Listing

> List directory contents and browse the filesystem in HopX sandboxes. Navigate directories, view file metadata, filter files by name or pattern, and discover generated outputs. Learn how to list files and directories using Python and JavaScript SDKs or REST API. Includes examples for directory navigation and file discovery.

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

<Note>
  You can list contents of allowed paths like `/workspace` and `/tmp`. Listing system directories may be restricted for security.
</Note>

## Basic Listing

List files in a directory:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    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()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

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

    // List directory contents
    const files = await sandbox.files.list('/workspace');
    console.log(`Found ${files.length} items`);

    for (const file of files) {
      if (file.isFile) {
        console.log(`📄 ${file.name} (${(file.size / 1024).toFixed(2)} KB)`);
      } else {
        console.log(`📁 ${file.name}/`);
      }
    }

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## File Information

Access detailed file information:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    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()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

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

    // List and get file info
    const files = await sandbox.files.list('/workspace');
    for (const file of files) {
      if (file.name === 'data.txt') {
        console.log(`Name: ${file.name}`);
        console.log(`Path: ${file.path}`);
        console.log(`Size: ${file.size} bytes`);
        console.log(`Size (KB): ${(file.size / 1024).toFixed(2)} KB`);
        console.log(`Size (MB): ${(file.size / 1024 / 1024).toFixed(2)} MB`);
        console.log(`Is file: ${file.isFile}`);
        console.log(`Is directory: ${file.isDirectory}`);
        console.log(`Permissions: ${file.permissions}`);
        console.log(`Modified: ${file.modifiedTime}`);
      }
    }

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Filtering Files

Filter files by type or pattern:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    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()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

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

    // List only Python files
    const files = await sandbox.files.list('/workspace');
    const pythonFiles = files.filter(f => f.isFile && f.name.endsWith('.py'));
    console.log(`Python files: ${pythonFiles.length}`);
    for (const f of pythonFiles) {
      console.log(`  ${f.name}`);
    }

    // List only directories
    const directories = files.filter(f => f.isDirectory);
    console.log(`\nDirectories: ${directories.length}`);
    for (const d of directories) {
      console.log(`  ${d.name}/`);
    }

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Recursive Listing

List files recursively by traversing directories:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    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()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

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

    async function listRecursive(path = '/workspace', indent = 0) {
      const items = await sandbox.files.list(path);
      for (const item of items) {
        const prefix = '  '.repeat(indent);
        if (item.isDirectory) {
          console.log(`${prefix}📁 ${item.name}/`);
          await listRecursive(item.path, indent + 1);
        } else {
          console.log(`${prefix}📄 ${item.name} (${(item.size / 1024).toFixed(2)} KB)`);
        }
      }
    }

    console.log('Directory structure:');
    await listRecursive('/workspace');

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Sorting and Filtering

Sort files by size, name, or date:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    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()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

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

    // List and sort by size
    const files = await sandbox.files.list('/workspace');
    const filesOnly = files.filter(f => f.isFile);

    // Sort by size (largest first)
    const sortedBySize = filesOnly.sort((a, b) => b.size - a.size);
    console.log('Files sorted by size:');
    for (const f of sortedBySize) {
      console.log(`  ${f.name}: ${(f.size / 1024).toFixed(2)} KB`);
    }

    // Sort by name
    const sortedByName = filesOnly.sort((a, b) => a.name.localeCompare(b.name));
    console.log('\nFiles sorted by name:');
    for (const f of sortedByName) {
      console.log(`  ${f.name}`);
    }

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Complete Example

Here's a complete example showing directory listing:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    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()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

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

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

    // List and display structure
    async function displayTree(path, prefix = '') {
      const files = await sandbox.files.list(path);
      files.sort((a, b) => {
        if (a.isDirectory !== b.isDirectory) {
          return a.isDirectory ? -1 : 1;
        }
        return a.name.localeCompare(b.name);
      });
      
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const isLast = i === files.length - 1;
        const currentPrefix = isLast ? '└── ' : '├── ';
        console.log(`${prefix}${currentPrefix}${file.name}`);
        
        if (file.isDirectory) {
          const nextPrefix = prefix + (isLast ? '    ' : '│   ');
          await displayTree(file.path, nextPrefix);
        }
      }
    }

    console.log('Project structure:');
    await displayTree('/workspace/myproject');

    // Summary
    const allFiles = await sandbox.files.list('/workspace/myproject');
    const totalSize = allFiles.filter(f => f.isFile).reduce((sum, f) => sum + f.size, 0);
    console.log(`\nTotal files: ${allFiles.filter(f => f.isFile).length}`);
    console.log(`Total size: ${(totalSize / 1024).toFixed(2)} KB`);

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Best Practices

<Steps>
  <Step title="1. Check Directory Existence">
    Use `files.exists()` before listing to avoid errors, or handle `FileNotFoundError` appropriately.
  </Step>

  <Step title="2. Filter by Type">
    Use `is_file` and `is_dir` properties to filter files and directories.
  </Step>

  <Step title="3. Sort for Display">
    Sort files by name, size, or date for better user experience.
  </Step>

  <Step title="4. Use Recursive Listing">
    For nested structures, implement recursive listing to show complete directory trees.
  </Step>

  <Step title="5. Handle Large Directories">
    For directories with many files, consider pagination or filtering to avoid performance issues.
  </Step>
</Steps>

## Related

* **[Reading Files](/core-concepts/filesystem/reading)** - Read file contents
* **[Writing Files](/core-concepts/filesystem/writing)** - Write files to sandboxes
* **SDK**: [sandbox.files.list()](/sdk/python/files#list) - Python SDK method
* **API**: [GET /files/list](/api/vm-agent/list-files) - VM Agent API endpoint
* [CLI File Operations](/cli/commands/files) - File operations from CLI

## Next Steps

* Learn about [Reading Files](/core-concepts/filesystem/reading) to access file contents
* Explore [Writing Files](/core-concepts/filesystem/writing) to create files
* Review [Watching Files](/core-concepts/filesystem/watching) for real-time file monitoring
