File Operations Examples

Learn how to work with files in the AI Computer sandbox environment. These examples demonstrate common file operations and best practices.

Reading and Writing Files

Basic file operations within the sandbox:

1import asyncio
2from ai_computer import SandboxClient
3
4async def file_operations():
5    client = SandboxClient()
6    await client.setup()
7    
8    try:
9        # Write and read a text file
10        code = """
11# Writing to a file
12with open('example.txt', 'w') as f:
13    f.write('Hello from AI Computer!\n')
14    f.write('This is a test file.\n')
15
16# Reading from the file
17with open('example.txt', 'r') as f:
18    content = f.read()
19    print('File contents:')
20    print(content)
21"""
22        response = await client.execute_code(code)
23        if response.success:
24            print(response.data['output'])
25        else:
26            print("Error:", response.error)
27            
28    finally:
29        await client.cleanup()
30
31asyncio.run(file_operations())

Working with Binary Files

Handle binary file operations:

1import asyncio
2from ai_computer import SandboxClient
3
4async def binary_operations():
5    client = SandboxClient()
6    await client.setup()
7    
8    try:
9        # Create and read a binary file
10        code = """
11import struct
12
13# Write binary data
14with open('data.bin', 'wb') as f:
15    # Write some integers as binary
16    numbers = [1, 2, 3, 4, 5]
17    for num in numbers:
18        f.write(struct.pack('i', num))
19
20# Read binary data
21with open('data.bin', 'rb') as f:
22    # Read and unpack the integers
23    data = []
24    while True:
25        chunk = f.read(4)  # Read 4 bytes (size of int)
26        if not chunk:
27            break
28        number = struct.unpack('i', chunk)[0]
29        data.append(number)
30    
31    print('Read numbers:', data)
32"""
33        response = await client.execute_code(code)
34        if response.success:
35            print(response.data['output'])
36        else:
37            print("Error:", response.error)
38            
39    finally:
40        await client.cleanup()
41
42asyncio.run(binary_operations())

File Management

Manage files and directories in the sandbox:

1import asyncio
2from ai_computer import SandboxClient
3
4async def file_management():
5    client = SandboxClient()
6    await client.setup()
7    
8    try:
9        # Demonstrate file and directory operations
10        code = """
11import os
12import shutil
13
14# Create a directory
15os.makedirs('data', exist_ok=True)
16print("Created 'data' directory")
17
18# Create some files
19for i in range(3):
20    filename = f'data/file{i}.txt'
21    with open(filename, 'w') as f:
22        f.write(f'Content of file {i}\n')
23    print(f"Created {filename}")
24
25# List directory contents
26print("\nDirectory contents:")
27for item in os.listdir('data'):
28    path = os.path.join('data', item)
29    size = os.path.getsize(path)
30    print(f"- {item} ({size} bytes)")
31
32# Move a file
33os.rename('data/file0.txt', 'data/moved.txt')
34print("\nMoved file0.txt to moved.txt")
35
36# Delete a file
37os.remove('data/file1.txt')
38print("Deleted file1.txt")
39
40# Clean up directory
41shutil.rmtree('data')
42print("Removed 'data' directory")
43"""
44        response = await client.execute_code(code)
45        if response.success:
46            print(response.data['output'])
47        else:
48            print("Error:", response.error)
49            
50    finally:
51        await client.cleanup()
52
53asyncio.run(file_management())

Error Handling

Handle common file operation errors:

1import asyncio
2from ai_computer import SandboxClient
3
4async def handle_file_errors():
5    client = SandboxClient()
6    await client.setup()
7    
8    try:
9        code = """
10import os
11
12def safe_file_operation(operation):
13    try:
14        operation()
15        return True
16    except FileNotFoundError as e:
17        print(f"File not found: {e}")
18    except PermissionError as e:
19        print(f"Permission denied: {e}")
20    except IOError as e:
21        print(f"IO error: {e}")
22    return False
23
24# Try to read non-existent file
25safe_file_operation(lambda: open('nonexistent.txt', 'r'))
26
27# Try to write to read-only file
28with open('readonly.txt', 'w') as f:
29    f.write('test')
30os.chmod('readonly.txt', 0o444)  # Make read-only
31safe_file_operation(lambda: open('readonly.txt', 'w'))
32
33# Try to create file in non-existent directory
34safe_file_operation(lambda: open('nonexistent/file.txt', 'w'))
35"""
36        response = await client.execute_code(code)
37        if response.success:
38            print(response.data['output'])
39        else:
40            print("Error:", response.error)
41            
42    finally:
43        await client.cleanup()
44
45asyncio.run(handle_file_errors())

Best Practices

1. Use Context Managers

Always use 'with' statements for file operations to ensure proper cleanup.

2. Handle File Errors

Implement proper error handling for all file operations.

3. Clean Up Resources

Remove temporary files and directories when they are no longer needed.

4. Use Appropriate Modes

Choose the correct file modes (text vs binary) based on the data being handled.