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())
Using the File System Module
The FileSystemModule provides dedicated methods for file operations:
1import asyncio
2from ai_computer import SandboxClient
3
4async def fs_module_example():
5 client = SandboxClient()
6 await client.setup()
7
8 try:
9 # Write content to a file using the fs module
10 write_response = await client.fs.write_file(
11 path="data.txt",
12 content="This content was written using the fs module."
13 )
14
15 if write_response.success:
16 print(f"File written successfully to {write_response.data.get('path')}")
17
18 # Read the file content using the fs module
19 read_response = await client.fs.read_file("data.txt")
20
21 if read_response.success:
22 print("File content:")
23 print(read_response.data.get('content'))
24 else:
25 print(f"Failed to read file: {read_response.error}")
26 else:
27 print(f"Failed to write file: {write_response.error}")
28
29 finally:
30 await client.cleanup()
31
32asyncio.run(fs_module_example())
Uploading and Downloading Files
Transfer files between your local environment and the sandbox:
1import asyncio
2from pathlib import Path
3from ai_computer import SandboxClient
4
5async def file_transfer():
6 client = SandboxClient()
7 await client.setup()
8
9 try:
10 # Create a local file to upload
11 local_file = Path("local_test.txt")
12 local_file.write_text("This is a test file for upload.")
13
14 # Upload the file to the sandbox
15 upload_response = await client.upload_file(
16 file_path=local_file,
17 destination="uploads" # Relative path in the sandbox
18 )
19
20 if upload_response.success:
21 print(f"File uploaded to {upload_response.path}")
22 print(f"Size: {upload_response.size} bytes")
23
24 # Verify the file in the sandbox
25 verify_code = """
26import os
27
28# Create directory if it doesn't exist
29os.makedirs('uploads', exist_ok=True)
30
31# Check if file exists
32if os.path.exists('uploads/local_test.txt'):
33 with open('uploads/local_test.txt', 'r') as f:
34 content = f.read()
35 print(f"File content: {content}")
36else:
37 print("File not found")
38"""
39 verify_result = await client.execute_code(verify_code)
40 print(verify_result.data.get('output', ''))
41
42 # Download the file with a different name
43 download_path = Path("downloaded_test.txt")
44 download_response = await client.download_file(
45 remote_path="uploads/local_test.txt",
46 local_path=download_path
47 )
48
49 if download_response.success:
50 print(f"File downloaded to {download_response.path}")
51 print(f"Content: {download_path.read_text()}")
52 else:
53 print(f"Download failed: {download_response.error}")
54 else:
55 print(f"Upload failed: {upload_response.error}")
56
57 # Clean up local files
58 local_file.unlink(missing_ok=True)
59 download_path.unlink(missing_ok=True)
60
61 finally:
62 await client.cleanup()
63
64asyncio.run(file_transfer())
Working with Bytes and Memory
Upload and download file content directly in memory:
1import asyncio
2from io import BytesIO
3from ai_computer import SandboxClient
4
5async def memory_operations():
6 client = SandboxClient()
7 await client.setup()
8
9 try:
10 # Create some binary content
11 binary_content = b"Binary data: \x00\x01\x02\x03\x04"
12
13 # Upload bytes directly
14 bytes_upload = await client.upload_bytes(
15 content=binary_content,
16 filename="binary_test.bin",
17 destination="uploads"
18 )
19
20 if bytes_upload.success:
21 print(f"Binary data uploaded to {bytes_upload.path}")
22
23 # Download the binary data to memory
24 binary_download = await client.download_bytes("uploads/binary_test.bin")
25
26 if isinstance(binary_download, bytes):
27 print(f"Downloaded {len(binary_download)} bytes")
28 print(f"Content matches: {binary_download == binary_content}")
29 else:
30 print(f"Binary download failed: {binary_download.error}")
31 else:
32 print(f"Binary upload failed: {bytes_upload.error}")
33
34 # Create a BytesIO object with some data
35 buffer = BytesIO()
36 buffer.write(b"Hello from BytesIO!\n")
37 buffer.write(b"This is streamed content.")
38 buffer.seek(0) # Reset position for reading
39
40 # Upload the BytesIO content
41 stream_upload = await client.upload_bytes(
42 content=buffer,
43 filename="stream.txt",
44 content_type="text/plain",
45 destination="uploads"
46 )
47
48 if stream_upload.success:
49 print(f"Stream uploaded to {stream_upload.path}")
50
51 # Read the file using the fs module
52 read_response = await client.fs.read_file("uploads/stream.txt")
53 if read_response.success:
54 print(f"File content: {read_response.data.get('content')}")
55 else:
56 print(f"Failed to read file: {read_response.error}")
57 else:
58 print(f"Stream upload failed: {stream_upload.error}")
59
60 finally:
61 await client.cleanup()
62
63asyncio.run(memory_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 # Try to read a non-existent file using the fs module
10 read_response = await client.fs.read_file("nonexistent.txt")
11 if not read_response.success:
12 print(f"Expected error: {read_response.error}")
13
14 # Try to upload a non-existent file
15 upload_response = await client.upload_file("nonexistent.txt")
16 if not upload_response.success:
17 print(f"Expected error: {upload_response.error}")
18
19 # Try to download a non-existent file
20 download_response = await client.download_file("nonexistent.txt")
21 if not download_response.success:
22 print(f"Expected error: {download_response.error}")
23
24 # Handle file errors in code execution
25 code = """
26import os
27
28def safe_file_operation(operation):
29 try:
30 operation()
31 return True
32 except FileNotFoundError as e:
33 print(f"File not found: {e}")
34 except PermissionError as e:
35 print(f"Permission denied: {e}")
36 except IOError as e:
37 print(f"IO error: {e}")
38 return False
39
40# Try to read non-existent file
41safe_file_operation(lambda: open('nonexistent.txt', 'r'))
42
43# Try to create file in non-existent directory
44safe_file_operation(lambda: open('nonexistent/file.txt', 'w'))
45"""
46 response = await client.execute_code(code)
47 if response.success:
48 print(response.data['output'])
49 else:
50 print("Error:", response.error)
51
52 finally:
53 await client.cleanup()
54
55asyncio.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 Relative Paths
Use relative paths within the sandbox to avoid permission issues.
5. Consider Memory Efficiency
For large files, use the file streaming capabilities to reduce memory usage.