Is it possible to get the value of a specific cell when using prettytable?
I have the following code to iterate through all rows of a simple table.
from prettytable import PrettyTable
table = PrettyTable(["Column 1", "Column 2", "Column 3"])
table.add_row(["A", "B", "C"])
table.add_row(["F", "O", "O"])
table.add_row(["B", "A", "R"])
for row in table:
print(row)
This example prints the following 3 tables:
+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
| A | B | C |
+----------+----------+----------+
+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
| F | O | O |
+----------+----------+----------+
+----------+----------+----------+
| Column 1 | Column 2 | Column 3 |
+----------+----------+----------+
| B | A | R |
+----------+----------+----------+
How is it possible to get only the value of Column 1
, Column 2
or Column 3
of a row?
The quickest way to get data into a PrettyTable object is to build a table from data which is already stored in some table-like format. The variable pt will then be a fully populated PrettyTable object. Note that the first row of the CSV file will be interpreted as the field names and used for the table header.
We'll use the PrettyTable() class to define, modify, and print tables in Python. For databases with a Python library that conforms to the Python DB-API – an SQLite database, for example – you can define a cursor object then build a table using the from_db_cursor() function from prettytable .
Download the latest version of PrettyTable from the Downloads tab at this Google code project site. Save the file as "prettytable.py" (not prettytable-x.y.py) in your Python installation's "site-packages" directory.
It looks like what you want to do is get a subset of the data, from the documentation here, try:
from prettytable import PrettyTable
table = PrettyTable(["Column 1", "Column 2", "Column 3"])
table.add_row(["A", "B", "C"])
table.add_row(["F", "O", "O"])
table.add_row(["B", "A", "R"])
for row in table:
print row.get_string(fields=["Column 1"]) # Column 1
Edit: It looks like you don't want the headers or border, just the value, in which case, this should work:
from prettytable import PrettyTable
table = PrettyTable(["Column 1", "Column 2", "Column 3"])
table.add_row(["A", "B", "C"])
table.add_row(["F", "O", "O"])
table.add_row(["B", "A", "R"])
for row in table:
row.border = False
row.header = False
print row.get_string(fields=["Column 1"]).strip() # Column 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With