or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli-tables.mdcore-parser.mdindex.mdterminal-utils.mdtext-tables.md

text-tables.mddocs/

0

# Text Tables

1

2

The TextTable module provides tabular data representation and formatting capabilities for displaying parsed results as structured tables with various output formats including CSV, formatted text, and HTML.

3

4

## Core Imports

5

6

```python

7

from textfsm import texttable

8

from textfsm.texttable import TextTable, Row

9

from textfsm.texttable import TableError

10

```

11

12

## Capabilities

13

14

### TextTable Class

15

16

Main table class for storing, manipulating, and formatting tabular data with support for multiple display formats.

17

18

```python { .api }

19

class TextTable(object):

20

def __init__(self, row_class=Row):

21

"""

22

Initialize text table.

23

24

Args:

25

row_class: Row class to use for table rows (default: Row)

26

"""

27

28

def Append(self, row_data):

29

"""

30

Add row to table.

31

32

Args:

33

row_data (list): List of values for the row

34

"""

35

36

def extend(self, table, keys=None):

37

"""

38

Add multiple rows from another table.

39

40

Args:

41

table: TextTable or list of rows to extend with

42

keys (list): Specific keys/columns to copy (optional)

43

"""

44

45

def CsvToTable(self, buf, header=True, separator=','):

46

"""

47

Populate table from CSV data.

48

49

Args:

50

buf: CSV data as string or file-like object

51

header (bool): True if first row contains headers

52

separator (str): Field separator character

53

54

Returns:

55

int: Number of rows processed

56

"""

57

58

def LabelValueTable(self, data):

59

"""

60

Create label-value formatted table display.

61

62

Args:

63

data: Data to format as label-value pairs

64

65

Returns:

66

str: Formatted label-value representation

67

"""

68

69

def FormattedTable(self, width=80, force_display=False, ml_delimiter=True, color=True, display_header=True, columns=None):

70

"""

71

Get formatted table as string.

72

73

Args:

74

width (int): Maximum width for table formatting

75

force_display (bool): Force display even if table is empty

76

ml_delimiter (bool): Use multi-line delimiter

77

color (bool): Include color formatting

78

display_header (bool): Show column headers

79

columns (list): Specific columns to display

80

81

Returns:

82

str: Formatted table with borders and alignment

83

"""

84

85

def NewRow(self, value=''):

86

"""

87

Create new empty row.

88

89

Args:

90

value: Default value for row cells

91

92

Returns:

93

Row: Empty row object

94

"""

95

96

def Reset(self):

97

"""Clear all table data and headers."""

98

99

def Remove(self, row):

100

"""

101

Remove row from table.

102

103

Args:

104

row: Row object to remove

105

"""

106

107

def sort(self, cmp=None, key=None, reverse=False):

108

"""

109

Sort table rows.

110

111

Args:

112

cmp: Comparison function (deprecated)

113

key: Key function for sorting

114

reverse (bool): Sort in reverse order

115

"""

116

117

def Filter(self, function=None):

118

"""

119

Filter table rows using a function.

120

121

Args:

122

function (callable): Function to test each row

123

124

Returns:

125

TextTable: New table with filtered rows

126

"""

127

128

def Map(self, function):

129

"""

130

Apply function to each row in table.

131

132

Args:

133

function (callable): Function to apply to each row

134

135

Returns:

136

TextTable: New table with transformed rows

137

"""

138

139

def RowWith(self, column, value):

140

"""

141

Find first row with specific column value.

142

143

Args:

144

column (str): Column name to search

145

value: Value to match

146

147

Returns:

148

Row: First matching row, or None if not found

149

"""

150

151

def index(self, name=None):

152

"""

153

Get column index by name.

154

155

Args:

156

name (str): Column name to find

157

158

Returns:

159

int: Column index

160

"""

161

162

def AddColumn(self, column, default='', col_index=-1):

163

"""

164

Add column to table.

165

166

Args:

167

column (str): Column name

168

default: Default value for existing rows

169

col_index (int): Position to insert column (-1 for end)

170

"""

171

172

def __repr__(self):

173

"""String representation of table."""

174

175

def __str__(self):

176

"""Formatted string representation."""

177

178

def __iter__(self):

179

"""Iterate over table rows."""

180

181

def __next__(self):

182

"""Get next row in iteration."""

183

184

def __getitem__(self, row):

185

"""Get row by index."""

186

187

def __contains__(self, name):

188

"""Check if column name exists."""

189

190

def __add__(self, other):

191

"""Concatenate tables."""

192

193

def __copy__(self):

194

"""Create shallow copy."""

195

196

@property

197

def header(self):

198

"""List of column headers."""

199

200

@property

201

def table(self):

202

"""List of Row objects."""

203

204

@property

205

def row(self):

206

"""Current row object."""

207

208

@property

209

def row_index(self):

210

"""Current row index."""

211

212

@property

213

def size(self):

214

"""Number of rows in table."""

215

216

@property

217

def separator(self):

218

"""Field separator character."""

219

220

@property

221

def row_class(self):

222

"""Row class used for creating rows."""

223

```

224

225

### Row Class

226

227

Represents individual table rows as ordered dictionaries with table context and formatting capabilities.

228

229

```python { .api }

230

class Row(dict):

231

def __init__(self, *args, **kwargs):

232

"""

233

Initialize table row.

234

235

Args:

236

*args: Arguments passed to dict constructor

237

**kwargs: Keyword arguments passed to dict constructor

238

"""

239

240

def __getitem__(self, column):

241

"""Get value by column name or index."""

242

243

def __setitem__(self, column, value):

244

"""Set value by column name or index."""

245

246

def __contains__(self, value):

247

"""Check if value exists in row."""

248

249

def __iter__(self):

250

"""Iterate over row values."""

251

252

def __len__(self):

253

"""Get number of columns in row."""

254

255

def __str__(self):

256

"""String representation of row."""

257

258

def __repr__(self):

259

"""Debug representation of row."""

260

261

def get(self, column, default_value=None):

262

"""

263

Get value from column with default.

264

265

Args:

266

column: Column name or index

267

default_value: Default value if column not found

268

269

Returns:

270

Value from column or default

271

"""

272

273

def index(self, column):

274

"""

275

Get index of column.

276

277

Args:

278

column: Column name

279

280

Returns:

281

int: Column index

282

"""

283

284

def iterkeys(self):

285

"""

286

Iterate over column names.

287

288

Returns:

289

Iterator: Column name iterator

290

"""

291

292

def items(self):

293

"""

294

Get column name-value pairs.

295

296

Returns:

297

list: List of (name, value) tuples

298

"""

299

300

def Insert(self, key, value, row_index):

301

"""

302

Insert value at specific position.

303

304

Args:

305

key: Column name

306

value: Value to insert

307

row_index (int): Position to insert at

308

"""

309

310

@property

311

def header(self):

312

"""List of column headers from parent table."""

313

314

@property

315

def header(self):

316

"""List of column headers from parent table."""

317

318

@property

319

def values(self):

320

"""List of row values in column order."""

321

322

@property

323

def row(self):

324

"""Row values as list."""

325

326

@property

327

def table(self):

328

"""Parent TextTable instance."""

329

330

@property

331

def color(self):

332

"""Row color specification."""

333

```

334

335

## Usage Examples

336

337

### Basic Table Operations

338

339

```python

340

from textfsm import texttable

341

342

# Create table with headers

343

table = texttable.TextTable(['Name', 'Age', 'City'])

344

345

# Add rows

346

table.Append(['Alice', '25', 'New York'])

347

table.Append(['Bob', '30', 'San Francisco'])

348

table.Append(['Charlie', '35', 'Chicago'])

349

350

# Display formatted table

351

print(table.FormattedTable())

352

```

353

354

### Working with CSV Data

355

356

```python

357

from textfsm import texttable

358

359

# Create table from CSV

360

csv_data = """Name,Age,City

361

Alice,25,New York

362

Bob,30,San Francisco

363

Charlie,35,Chicago"""

364

365

table = texttable.TextTable()

366

table.CsvToTable(csv_data)

367

368

# Convert back to CSV

369

csv_output = table.TableToCSV()

370

print(csv_output)

371

```

372

373

### Label-Value Format Processing

374

375

```python

376

from textfsm import texttable

377

378

# Parse label-value formatted data

379

data = """

380

Name: Alice

381

Age: 25

382

City: New York

383

---

384

Name: Bob

385

Age: 30

386

City: San Francisco

387

"""

388

389

table = texttable.TextTable()

390

table.LabelValueTable(data, separator=':', skip_line=lambda x: x.startswith('---'))

391

```

392

393

### Row Manipulation

394

395

```python

396

from textfsm import texttable

397

398

table = texttable.TextTable(['Name', 'Score'])

399

400

# Create and populate rows

401

row1 = table.NewRow()

402

row1.AssignVar('Name', 'Alice')

403

row1.AssignVar('Score', '95')

404

table.Append(row1.row())

405

406

# Access row data

407

for row in table.table:

408

name = row.GetVar('Name')

409

score = row.GetVar('Score')

410

print(f"{name}: {score}")

411

```

412

413

### Table Sorting and Filtering

414

415

```python

416

from textfsm import texttable

417

418

table = texttable.TextTable(['Name', 'Score', 'Grade'])

419

table.Append(['Alice', '95', 'A'])

420

table.Append(['Bob', '87', 'B'])

421

table.Append(['Charlie', '92', 'A'])

422

423

# Sort by score (descending)

424

table.sort(['Score'])

425

426

# Filter rows (example would require actual implementation)

427

# table.Filter(lambda row: int(row.GetVar('Score')) > 90)

428

429

# Add new column

430

table.AddColumn('Pass', ['Yes', 'Yes', 'Yes'])

431

```

432

433

### Integration with TextFSM

434

435

```python

436

import io

437

import textfsm

438

from textfsm import texttable

439

440

# Parse with TextFSM

441

template = """

442

Value NAME (\S+)

443

Value SCORE (\d+)

444

445

Start

446

^${NAME} scored ${SCORE} points -> Record

447

"""

448

449

text = "Alice scored 95 points\nBob scored 87 points"

450

fsm = textfsm.TextFSM(io.StringIO(template))

451

results = fsm.ParseText(text)

452

453

# Create formatted table

454

table = texttable.TextTable(fsm.header)

455

table.extend(results)

456

print(table.FormattedTable())

457

```

458

459

### Custom Formatting

460

461

```python

462

from textfsm import texttable

463

464

table = texttable.TextTable(['Product', 'Price', 'Stock'])

465

table.Append(['Widget A', '$19.99', '150'])

466

table.Append(['Widget B', '$29.99', '75'])

467

468

# Get formatted output with custom options

469

formatted = table.FormattedTable()

470

print(formatted)

471

472

# Export to different formats

473

csv_data = table.TableToCSV()

474

```