from praisonaiagents import Agent
from praisonaiagents import read_file , write_file , list_files
agent = Agent (
name = " File Assistant " ,
instructions = " Read, write, and organise files safely. " ,
tools =[ read_file , write_file , list_files ],
)
agent . start ( " List files in ./src and summarise README.md " )
The user describes a file task; the agent uses file tools to read paths and return a concise answer.
Prerequisites
Python 3.10 or higher
PraisonAI Agents package installed
Basic understanding of file operations
Use File Tools to perform file system operations with AI agents.
Install Dependencies
First, install the required package: pip install praisonaiagents
Import Components
Import the necessary components: from praisonaiagents import Agent , Task , AgentTeam
from praisonaiagents import read_file , write_file , list_files , get_file_info , copy_file , move_file , delete_file
Create Agent
Create a file management agent: file_agent = Agent (
name = " FileManager " ,
role = " File System Specialist " ,
goal = " Manage files and directories efficiently. " ,
backstory = " Expert in file system operations and organization. " ,
tools =[ read_file , write_file , list_files , get_file_info , copy_file , move_file , delete_file ],
reflection = False
)
Define Task
Define the file management task: file_task = Task (
description = " Organize files in the downloads directory by file type. " ,
expected_output = " Organized directory structure with categorized files. " ,
agent = file_agent ,
name = " organize_files "
)
Run Agent
Initialize and run the agent: agents = AgentTeam (
agents =[ file_agent ],
tasks =[ file_task ],
process = " sequential "
)
agents . start ()
What are File Tools? File Tools provide file system management capabilities for AI agents:
File operations (read, write, copy, move)
Directory management
File information retrieval
File organization
Path manipulation
Key Components
File Agent Create specialized file agents: Agent ( tools =[ read_file , write_file , list_files , get_file_info , copy_file , move_file , delete_file ])
File Task Define file tasks: Task ( description = " file_operation " )
Process Types Sequential or parallel processing:
File Options Customize file operations: recursive = True , overwrite = False
Available Functions
from praisonaiagents import read_file
from praisonaiagents import write_file
from praisonaiagents import list_files
from praisonaiagents import get_file_info
from praisonaiagents import copy_file
from praisonaiagents import move_file
from praisonaiagents import delete_file
Function Details
read_file(filepath, encoding=‘utf-8’, offset=None, limit=None, line_numbers=True, max_line_chars=2000)
Reads a windowed, line-numbered view of a file so a coding agent can reference exact lines for follow-up edits.
Argument Type Default Description filepathstr— Path to the file. encodingstr'utf-8'File encoding. offsetint | NoneNone (start of file)1-based first line to read. limitint | NoneNone (up to 2000 lines)Maximum lines to read. Negative → empty window. line_numbersboolTruePrefix each line with its 1-based number. Set False (with no offset/limit) for exact raw content. max_line_charsint2000Truncate any single line longer than this with "... (line truncated)". Negative disables.
Default output is line-numbered with a right-aligned gutter (width = max(len(str(last_line)), 6), tab-separated):
When the window doesn’t reach the end of the file, a paging hint is appended so the agent knows where to continue:
... (showing lines 1-2000 of 4573; call again with offset=2001 for more)
# Default — line-numbered output
content = read_file ( " example.txt " )
# With specific encoding
content = read_file ( " data.txt " , encoding = " latin-1 " )
# Page a large file — first page; paging hint shows where to continue
page1 = read_file ( " app.py " , offset = 1 , limit = 2000 )
# Continue where the hint pointed
page2 = read_file ( " app.py " , offset = 2001 , limit = 2000 )
# Restore pre-2527 raw output (no gutter, no windowing)
raw = read_file ( " small.txt " , line_numbers = False )
# Returns: str
# Error case: Returns error message as string
Backwards compatibility: read_file(path, line_numbers=False) (with no offset or limit) returns the exact plain-string content identical to pre-2527 behaviour — useful when downstream code depends on the raw string shape.
write_file(filepath: str, content: str, encoding: str = ‘utf-8’)
Writes content to a file:
Creates directories if they don’t exist
Supports different encodings
Overwrites existing files
# Basic usage
success = write_file ( " output.txt " , " Hello World " )
# With specific encoding and nested path
success = write_file (
" path/to/data/output.txt " ,
" Content with special chars: áéíóú " ,
encoding = " utf-8 "
)
# Returns: bool (True if successful)
list_files(directory: str, pattern: Optional[str] = None)
Lists files in a directory:
Optional pattern matching
Detailed file information
Recursive directory support
# List all files
files = list_files ( " /path/to/directory " )
# With pattern matching
files = list_files ( " /path/to/directory " , pattern = " *.txt " )
# Returns: List[Dict[str, Union[str, int]]]
# Example: [
# {
# 'name': 'example.txt',
# 'path': '/path/to/directory/example.txt',
# 'size': 1024,
# 'modified': 1609459200.0,
# 'created': 1609459100.0
# },
# ...
# ]
get_file_info(filepath: str)
Gets detailed information about a file:
File metadata
Size and timestamps
Type information
Path details
# Get file information
info = get_file_info ( " example.txt " )
# Returns: Dict[str, Union[str, int]]
# Example: {
# 'name': 'example.txt',
# 'path': '/absolute/path/to/example.txt',
# 'size': 1024,
# 'modified': 1609459200.0,
# 'created': 1609459100.0,
# 'is_file': True,
# 'is_dir': False,
# 'extension': '.txt',
# 'parent': '/absolute/path/to'
# }
copy_file(src: str, dst: str)
Copies a file with metadata:
Preserves timestamps
Creates destination directories
Handles existing files
# Basic copy
success = copy_file ( " source.txt " , " destination.txt " )
# Copy to new directory
success = copy_file (
" data.txt " ,
" backup/2023/data_backup.txt "
)
# Returns: bool (True if successful)
move_file(src: str, dst: str)
Moves or renames a file:
Creates destination directories
Handles existing files
Cross-device moves
# Move file
success = move_file ( " old/path/file.txt " , " new/path/file.txt " )
# Rename file
success = move_file (
" document.txt " ,
" document_v2.txt "
)
# Returns: bool (True if successful)
delete_file(filepath: str)
Deletes a file:
Safe deletion
Error handling
Non-recursive (files only)
# Delete file
success = delete_file ( " unwanted.txt " )
# Returns: bool (True if successful)
Example Agent Configuration
from praisonaiagents import Agent
from praisonaiagents import (
read_file , write_file , list_files ,
get_file_info , copy_file , move_file , delete_file
)
agent = Agent (
name = " FileManager " ,
description = " An agent that manages files " ,
tools =[
read_file , write_file , list_files ,
get_file_info , copy_file , move_file , delete_file
]
)
Error Handling
All functions include comprehensive error handling:
File not found errors
Permission errors
Path errors
I/O errors
Encoding errors
Errors are handled consistently:
File operations return bool for success/failure
Information functions return error details in result
All errors are logged for debugging
Common Use Cases
File Organization:
# List and organize files by extension
files = list_files ( " downloads " , pattern = " *.* " )
for file in files :
ext = file [ ' extension ' ]
if ext :
dst = f "organized/ { ext [ 1 :] } / { file [ ' name ' ] } "
move_file ( file [ ' path ' ], dst )
File Backup:
# Create timestamped backups
import time
files = list_files ( " important_data " )
backup_time = time . strftime ( " %Y%m %d _%H%M%S " )
for file in files :
dst = f "backup/ { backup_time } / { file [ ' name ' ] } "
copy_file ( file [ ' path ' ], dst )
File Processing:
# Read, process, and write files (use line_numbers=False for plain-string input)
content = read_file ( " input.txt " , line_numbers = False )
processed = process_content ( content ) # Your processing function
write_file ( " output.txt " , processed )
Examples
Basic File Management Agent
from praisonaiagents import Agent , Task , AgentTeam
from praisonaiagents import read_file , write_file , list_files , get_file_info
# Create file management agent
file_agent = Agent (
name = " FileExpert " ,
role = " File Manager " ,
goal = " Process and organize files efficiently. " ,
backstory = " Expert in file system operations and organization. " ,
tools =[ read_file , write_file , list_files , get_file_info ],
reflection = False
)
# Define file task
file_task = Task (
description = " Organize and process documents. " ,
expected_output = " Organized file structure. " ,
agent = file_agent ,
name = " file_organization "
)
# Run agent
agents = AgentTeam (
agents =[ file_agent ],
tasks =[ file_task ],
process = " sequential "
)
agents . start ()
Advanced File Operations with Multiple Agents
# Create file IO agent
io_agent = Agent (
name = " FileIO " ,
role = " File IO Specialist " ,
goal = " Handle file read/write operations efficiently. " ,
tools =[ read_file , write_file ],
reflection = False
)
# Create file management agent
management_agent = Agent (
name = " FileManager " ,
role = " File Management Specialist " ,
goal = " Handle file organization and movement. " ,
tools =[ list_files , get_file_info , copy_file , move_file , delete_file ],
reflection = False
)
# Define tasks
io_task = Task (
description = " Read and write files. " ,
expected_output = " File operations completed successfully. " ,
agent = io_agent ,
name = " file_io "
)
management_task = Task (
description = " Organize and move files. " ,
expected_output = " File management completed successfully. " ,
agent = management_agent ,
name = " file_management "
)
# Run agents
agents = AgentTeam (
agents =[ io_agent , management_agent ],
tasks =[ io_task , management_task ],
process = " sequential "
)
agents . start ()
Best Practices
Configure agents with clear file management focus: Agent (
name = " FileManager " ,
role = " File System Specialist " ,
goal = " Manage files efficiently and safely " ,
tools =[ read_file , write_file , list_files , get_file_info , copy_file , move_file , delete_file ]
)
Define specific file operations: Task (
description = " Clean up downloads folder and organize by file type " ,
expected_output = " Organized directory structure "
)
Common Patterns
File Organization Pipeline
# Organization agent
organizer = Agent (
name = " Organizer " ,
role = " File Organizer " ,
tools =[ read_file , write_file , list_files , get_file_info , copy_file , move_file , delete_file ]
)
# Cleanup agent
cleaner = Agent (
name = " Cleaner " ,
role = " File Cleaner "
)
# Define tasks
organize_task = Task (
description = " Organize files by type " ,
agent = organizer
)
cleanup_task = Task (
description = " Remove temporary files " ,
agent = cleaner
)
# Run workflow
agents = AgentTeam (
agents =[ organizer , cleaner ],
tasks =[ organize_task , cleanup_task ]
)
## Related
< CardGroup cols ={ 2 } >
< Card title = " Custom Tools " icon = " wrench " href = " /docs/tools/custom " >
Build your own agent tools
</ Card >
< Card title = " Tools Overview " icon = " toolbox " href = " /docs/tools/tools " >
Browse PraisonAI tool documentation
</ Card >
</ CardGroup >