Back to Blog

Build AI Apps with Python: File System Tools — AI That Reads and Writes Files | Episode 9

Celest KimCelest Kim

Video: Build AI Apps with Python: File System Tools — AI That Reads and Writes Files | Episode 9 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Build AI Apps with Python: File System Tools — AI That Reads and Writes Files

In this tutorial, we create three essential file system tools in Python that enable AI to interact with files safely within a controlled workspace directory. These tools allow reading, writing, and listing files, demonstrating how AI can manage real-world data beyond just answering questions.

Code

import os

# Define a safe workspace directory for all file operations
WORKSPACE_DIR = "workspace"

# Ensure the workspace directory exists
os.makedirs(WORKSPACE_DIR, exist_ok=True)

def write_file(filename, content):
  """Write content to a file inside the workspace."""
  # Construct a secure file path inside the workspace
  filepath = os.path.join(WORKSPACE_DIR, filename)
  with open(filepath, "w", encoding="utf-8") as f:
    f.write(content)
  return f"File '{filename}' written successfully."

def read_file(filename):
  """Read and return the content of a file inside the workspace."""
  filepath = os.path.join(WORKSPACE_DIR, filename)
  if not os.path.exists(filepath):
    return f"Error: File '{filename}' does not exist."
  with open(filepath, "r", encoding="utf-8") as f:
    return f.read()

def list_directory():
  """List all files in the workspace directory."""
  return os.listdir(WORKSPACE_DIR)

# Example usage:
print(write_file("example.txt", "Hello, AI-powered file system!"))
print(list_directory())
print(read_file("example.txt"))

Key Points

  • Use a dedicated workspace directory to keep file operations safe and contained.
  • Construct file paths securely with os.path.join to avoid path traversal issues.
  • Check file existence with os.path.exists before reading to handle errors gracefully.
  • Implement separate functions for reading, writing, and listing files to modularize file system interactions.
  • The os module provides essential tools for managing files and directories in Python.