Reading and Writing Files in Agent Context
open(), pathlib.Path, reading CSV/JSON/TXT files from agent tools.
Why File I/O Matters for Agents
Agents frequently need to read configuration, store intermediate results, and write output reports. Python provides two primary ways to work with files: the built-in open() function and the modern pathlib module. Both are essential to know.
Every file operation should use a context manager (with statement) to ensure the file is closed even if an error occurs.
# Two ways to read a file
# Traditional open()
with open('config.txt', 'r', encoding='utf-8') as f:
content = f.read()
# Modern pathlib
from pathlib import Path
content = Path('config.txt').read_text(encoding='utf-8')
print(content)Reading Files with open()
The open() function takes a filename and a mode. For reading text, use mode 'r'. You can read the entire file at once with .read(), line by line with .readline(), or all lines into a list with .readlines().
Always specify encoding='utf-8' to avoid platform-specific encoding surprises.
# Read entire file at once
with open('report.txt', 'r', encoding='utf-8') as f:
full_text = f.read()
print(f'Read {len(full_text)} characters')
# Read line by line (memory-efficient for large files)
with open('large_log.txt', 'r', encoding='utf-8') as f:
for line in f: # iterate directly over file object
line = line.rstrip('\n')
if 'ERROR' in line:
print('Found error:', line)
# Read all lines into a list
with open('tasks.txt', 'r', encoding='utf-8') as f:
tasks = f.readlines() # includes '\n' at end of each
tasks = [t.strip() for t in tasks]All lessons in this course
- Reading and Writing Files in Agent Context
- Directory Traversal and File Discovery
- File Format Handling: CSV, JSON, and TXT
- Safe File Operations with Error Handling