Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Display tabular data in a visually appealing ASCII table format

License

NotificationsYou must be signed in to change notification settings

prettytable/prettytable

Repository files navigation

PyPI versionSupported Python versionsPyPI downloadsGitHub Actions statusCodecovLicenceCode style: BlackTidelift

PrettyTable lets you print tables in an attractive ASCII form:

+-----------+------+------------+-----------------+| City name | Area | Population | Annual Rainfall |+-----------+------+------------+-----------------+| Adelaide  | 1295 |  1158259   |      600.5      || Brisbane  | 5905 |  1857594   |      1146.4     || Darwin    | 112  |   120900   |      1714.7     || Hobart    | 1357 |   205556   |      619.5      || Melbourne | 1566 |  3806092   |      646.9      || Perth     | 5386 |  1554769   |      869.4      || Sydney    | 2058 |  4336374   |      1214.8     |+-----------+------+------------+-----------------+

Installation

Install via pip:

python -m pip install -U prettytable

Install latest development version:

python -m pip install -U git+https://github.com/prettytable/prettytable

Or fromrequirements.txt:

-e git://github.com/prettytable/prettytable.git#egg=prettytable

Demo

To see demo output, run:

python3 -m prettytable

Tutorial on how to use the PrettyTable API

Getting your data into (and out of) the table

Let's suppose you have a shiny new PrettyTable:

fromprettytableimportPrettyTabletable=PrettyTable()

and you want to put some data into it. You have a few options.

Row by row

You can add data one row at a time. To do this you can set the field names first usingthefield_names attribute, and then add the rows one at a time using theadd_rowmethod:

table.field_names= ["City name","Area","Population","Annual Rainfall"]table.add_row(["Adelaide",1295,1158259,600.5])table.add_row(["Brisbane",5905,1857594,1146.4])table.add_row(["Darwin",112,120900,1714.7])table.add_row(["Hobart",1357,205556,619.5])table.add_row(["Sydney",2058,4336374,1214.8])table.add_row(["Melbourne",1566,3806092,646.9])table.add_row(["Perth",5386,1554769,869.4])

All rows at once

When you have a list of rows, you can add them in one go withadd_rows:

table.field_names= ["City name","Area","Population","Annual Rainfall"]table.add_rows(    [        ["Adelaide",1295,1158259,600.5],        ["Brisbane",5905,1857594,1146.4],        ["Darwin",112,120900,1714.7],        ["Hobart",1357,205556,619.5],        ["Sydney",2058,4336374,1214.8],        ["Melbourne",1566,3806092,646.9],        ["Perth",5386,1554769,869.4],    ])

Column by column

You can add data one column at a time as well. To do this you use theadd_columnmethod, which takes two arguments - a string which is the name for the field the columnyou are adding corresponds to, and a list or tuple which contains the column data:

table.add_column("City name",["Adelaide","Brisbane","Darwin","Hobart","Sydney","Melbourne","Perth"])table.add_column("Area", [1295,5905,112,1357,2058,1566,5386])table.add_column("Population", [1158259,1857594,120900,205556,4336374,3806092,1554769])table.add_column("Annual Rainfall",[600.5,1146.4,1714.7,619.5,1214.8,646.9,869.4])

Mixing and matching

If you really want to, you can even mix and matchadd_row andadd_column and buildsome of your table in one way and some of it in the other. Tables built this way arekind of confusing for other people to read, though, so don't do this unless you have agood reason.

Importing data from a CSV file

If you have your table data in a comma-separated values file (.csv), you can read thisdata into a PrettyTable like this:

fromprettytableimportfrom_csvwithopen("myfile.csv")asfp:mytable=from_csv(fp)

Importing data from a database cursor

If you have your table data in a database which you can access using a library whichconfirms to the Python DB-API (e.g. an SQLite database accessible using thesqlitemodule), then you can build a PrettyTable using a cursor object, like this:

importsqlite3fromprettytableimportfrom_db_cursorconnection=sqlite3.connect("mydb.db")cursor=connection.cursor()cursor.execute("SELECT field1, field2, field3 FROM my_table")mytable=from_db_cursor(cursor)

Getting data out

There are three ways to get data out of a PrettyTable, in increasing order ofcompleteness:

  • Thedel_row method takes an integer index of a single row to delete.
  • Thedel_column method takes a field name of a single column to delete.
  • Theclear_rows method takes no arguments and deletes all the rows in the table - butkeeps the field names as they were so you that you can repopulate it with the samekind of data.
  • Theclear method takes no arguments and deletes all rows and all field names. It'snot quite the same as creating a fresh table instance, though - style relatedsettings, discussed later, are maintained.

Displaying your table in ASCII form

PrettyTable's main goal is to let you print tables in an attractive ASCII form, likethis:

+-----------+------+------------+-----------------+| City name | Area | Population | Annual Rainfall |+-----------+------+------------+-----------------+| Adelaide  | 1295 |  1158259   |      600.5      || Brisbane  | 5905 |  1857594   |      1146.4     || Darwin    | 112  |   120900   |      1714.7     || Hobart    | 1357 |   205556   |      619.5      || Melbourne | 1566 |  3806092   |      646.9      || Perth     | 5386 |  1554769   |      869.4      || Sydney    | 2058 |  4336374   |      1214.8     |+-----------+------+------------+-----------------+

You can print tables like this tostdout or get string representations of them.

Printing

To print a table in ASCII form, you can just do this:

print(table)

The oldtable.printt() method from versions 0.5 and earlier has been removed.

To pass options changing the look of the table, use theget_string() method documentedbelow:

print(table.get_string())

Stringing

If you don't want to actually print your table in ASCII form but just get a stringcontaining whatwould be printed if you useprint(table), you can use theget_string method:

mystring=table.get_string()

This string is guaranteed to look exactly the same as what would be printed by doingprint(table). You can now do all the usual things you can do with a string, like writeyour table to a file or insert it into a GUI.

The table can be displayed in several different formats usingget_formatted_string bychanging theout_format=<text|html|json|csv|latex|mediawiki>. This function passesthrough arguments to the functions that render the table, so additional arguments can begiven. This provides a way to let a user choose the output formatting.

defmy_cli_function(table_format:str='text'):  ...print(table.get_formatted_string(table_format))

Controlling which data gets displayed

If you like, you can restrict the output ofprint(table) ortable.get_string to onlythe fields or rows you like.

Thefields argument to these methods takes a list of field names to be printed:

print(table.get_string(fields=["City name","Population"]))

gives:

+-----------+------------+| City name | Population |+-----------+------------+| Adelaide  |  1158259   || Brisbane  |  1857594   || Darwin    |   120900   || Hobart    |   205556   || Melbourne |  3806092   || Perth     |  1554769   || Sydney    |  4336374   |+-----------+------------+

Thestart andend arguments take the index of the first and last row to printrespectively. Note that the indexing works like Python list slicing - to print the 2nd,3rd and 4th rows of the table, setstart to 1 (the first row is row 0, so the secondis row 1) and setend to 4 (the index of the 4th row, plus 1):

print(table.get_string(start=1,end=4))

prints:

+-----------+------+------------+-----------------+| City name | Area | Population | Annual Rainfall |+-----------+------+------------+-----------------+| Brisbane  | 5905 |    1857594 | 1146.4          || Darwin    | 112  |     120900 | 1714.7          || Hobart    | 1357 |     205556 | 619.5           |+-----------+------+------------+-----------------+

Filtering your table

You can make sure that your tables are filtered by givingget_string arow_filterkeyword argument, which must be a function with one argumentrow returning a Booleanvalue. Therow is the list of fields in a row.

For example, to print the example table we built earlier of Australian capital citydata, so that cities with a population with more than 1,000,000, we can do this:

deffilter_function(self,vals:list[str])->bool:returnvals[2]>999999print(table.get_string(row_filter=filter_function))

to get:

+-----------+------+------------+-----------------+| City name | Area | Population | Annual Rainfall |+-----------+------+------------+-----------------+|  Adelaide | 1295 |  1158259   |      600.5      ||  Brisbane | 5905 |  1857594   |      1146.4     ||   Sydney  | 2058 |  4336374   |      1214.8     || Melbourne | 1566 |  3806092   |      646.9      ||   Perth   | 5386 |  1554769   |      869.4      |+-----------+------+------------+-----------------+

Changing the alignment of columns

By default, all columns in a table are centre aligned.

All columns at once

You can change the alignment of all the columns in a table at once by assigning a onecharacter string to thealign attribute. The allowed strings are"l","r" and"c" for left, right and centre alignment, respectively:

table.align="r"print(table)

gives:

+-----------+------+------------+-----------------+| City name | Area | Population | Annual Rainfall |+-----------+------+------------+-----------------+|  Adelaide | 1295 |    1158259 |           600.5 ||  Brisbane | 5905 |    1857594 |          1146.4 ||    Darwin |  112 |     120900 |          1714.7 ||    Hobart | 1357 |     205556 |           619.5 || Melbourne | 1566 |    3806092 |           646.9 ||     Perth | 5386 |    1554769 |           869.4 ||    Sydney | 2058 |    4336374 |          1214.8 |+-----------+------+------------+-----------------+
One column at a time

You can also change the alignment of individual columns based on the corresponding fieldname by treating thealign attribute as if it were a dictionary.

table.align["City name"]="l"table.align["Area"]="c"table.align["Population"]="r"table.align["Annual Rainfall"]="c"print(table)

gives:

+-----------+------+------------+-----------------+| City name | Area | Population | Annual Rainfall |+-----------+------+------------+-----------------+| Adelaide  | 1295 |    1158259 |      600.5      || Brisbane  | 5905 |    1857594 |      1146.4     || Darwin    | 112  |     120900 |      1714.7     || Hobart    | 1357 |     205556 |      619.5      || Melbourne | 1566 |    3806092 |      646.9      || Perth     | 5386 |    1554769 |      869.4      || Sydney    | 2058 |    4336374 |      1214.8     |+-----------+------+------------+-----------------+
Sorting your table by a field

You can make sure that your ASCII tables are produced with the data sorted by oneparticular field by givingget_string asortby keyword argument, which must be astring containing the name of one field.

For example, to print the example table we built earlier of Australian capital citydata, so that the most populated city comes last, we can do this:

print(table.get_string(sortby="Population"))

to get:

+-----------+------+------------+-----------------+| City name | Area | Population | Annual Rainfall |+-----------+------+------------+-----------------+| Darwin    | 112  |   120900   |      1714.7     || Hobart    | 1357 |   205556   |      619.5      || Adelaide  | 1295 |  1158259   |      600.5      || Perth     | 5386 |  1554769   |      869.4      || Brisbane  | 5905 |  1857594   |      1146.4     || Melbourne | 1566 |  3806092   |      646.9      || Sydney    | 2058 |  4336374   |      1214.8     |+-----------+------+------------+-----------------+

If we want the most populated city to comefirst, we can also give areversesort=True argument.

If youalways want your tables to be sorted in a certain way, you can make the settinglong-term like this:

table.sortby="Population"print(table)print(table)print(table)

All three tables printed by this code will be sorted by population (you could dotable.reversesort = True as well, if you wanted). The behaviour will persist until youturn it off:

table.sortby=None

If you want to specify a custom sorting function, you can use thesort_key keywordargument. Pass this a function which accepts two lists of values and returns a negativeor positive value depending on whether the first list should appear before or after thesecond one. If your table has n columns, each list will have n+1 elements. Each listcorresponds to one row of the table. The first element will be whatever data is in therelevant row, in the column specified by thesort_by argument. The remaining nelements are the data in each of the table's columns, in order, including a repeatedinstance of the data in thesort_by column.

Adding sections to a table

You can divide your table into different sections using theadd_divider method ordivider argument toadd_row() or even toadd_rows(). This will add a dividing lineinto the table under the row who has this field set. So we can set up a table like this:

table=PrettyTable()table.field_names= ["City name","Area","Population","Annual Rainfall"]table.add_row(["Adelaide",1295,1158259,600.5])table.add_divider()table.add_row(["Brisbane",5905,1857594,1146.4],divider=True)table.add_rows(    [["Darwin",112,120900,1714.7],     ["Hobart",1357,205556,619.5]],divider=True)table.add_row(["Melbourne",1566,3806092,646.9])table.add_row(["Perth",5386,1554769,869.4])table.add_row(["Sydney",2058,4336374,1214.8])

to get a table like this:

+-----------+------+------------+-----------------+| City name | Area | Population | Annual Rainfall |+-----------+------+------------+-----------------+|  Adelaide | 1295 |  1158259   |      600.5      |+-----------+------+------------+-----------------+|  Brisbane | 5905 |  1857594   |      1146.4     |+-----------+------+------------+-----------------+|   Darwin  | 112  |   120900   |      1714.7     ||   Hobart  | 1357 |   205556   |      619.5      |+-----------+------+------------+-----------------+| Melbourne | 1566 |  3806092   |      646.9      ||   Perth   | 5386 |  1554769   |      869.4      ||   Sydney  | 2058 |  4336374   |      1214.8     |+-----------+------+------------+-----------------+

Any added dividers will be removed if a table is sorted.

Changing the appearance of your table - the easy way

By default, PrettyTable produces ASCII tables that look like the ones used in SQLdatabase shells. But it can print them in a variety of other formats as well. If theformat you want to use is common, PrettyTable makes this easy for you to do using theset_style method. If you want to produce an uncommon table, you'll have to do thingsslightly harder (see later).

Setting a table style

You can set the style for your table using theset_style method before any calls toprint orget_string. Here's how to print a table in Markdown format:

fromprettytableimportTableStyletable.set_style(TableStyle.MARKDOWN)print(table)

In addition toMARKDOWN you can use these in-built styles:

  • DEFAULT - The default look, used to undo any style changes you may have made
  • PLAIN_COLUMNS - A borderless style that works well with command line programs forcolumnar data
  • MSWORD_FRIENDLY - A format which works nicely with Microsoft Word's "Convert totable" feature
  • ORGMODE - A table style that fitsOrg mode syntax
  • SINGLE_BORDER andDOUBLE_BORDER - Styles that use continuous single/double borderlines with Box drawing characters for a fancier display on terminal

Other styles are likely to appear in future releases.

Changing the appearance of your table - the hard way

If you want to display your table in a style other than one of the in-built styleslisted above, you'll have to set things up the hard way.

Don't worry, it's not really that hard!

Style options

PrettyTable has a number of style options which control various aspects of how tablesare displayed. You have the freedom to set each of these options individually towhatever you prefer. Theset_style method just does this automatically for you.

The options are:

OptionDetails
borderA Boolean option (must beTrue orFalse). Controls whether a border is drawn inside and around the table.
preserve_internal_borderA Boolean option (must beTrue orFalse). Controls whether borders are still drawn within the table even whenborder=False.
headerA Boolean option (must beTrue orFalse). Controls whether the first row of the table is a header showing the names of all the fields.
hrulesControls printing of horizontal rules after rows. Allowed values:FRAME,HEADER,ALL,NONE.
HEADER,ALL,NONEThese are variables defined inside theprettytable module so make sure you import them or useprettytable.FRAME etc.
vrulesControls printing of vertical rules between columns. Allowed values:FRAME,ALL,NONE.
int_formatA string which controls the way integer data is printed. This works like:print("%<int_format>d" % data).
float_formatA string which controls the way floating point data is printed. This works like:print("%<float_format>f" % data).
custom_formatA dictionary of field and callable. This allows you to set any format you wantpf.custom_format["my_col_int"] = lambda f, v: f"{v:,}". The type of the callable isCallable[[str, Any], str]
padding_widthNumber of spaces on either side of column data (only used if left and right paddings areNone).
left_padding_widthNumber of spaces on left-hand side of column data.
right_padding_widthNumber of spaces on right-hand side of column data.
vertical_charSingle character string used to draw vertical lines. Default:|.
horizontal_charSingle character string used to draw horizontal lines. Default:-.
_horizontal_align_charSingle character string used to indicate column alignment in horizontal lines. Default:: for Markdown, otherwiseNone.
junction_charSingle character string used to draw line junctions. Default:+.
top_junction_charSingle character string used to draw top line junctions. Default:junction_char.
bottom_junction_charsingle character string used to draw bottom line junctions. Default:junction_char.
right_junction_charSingle character string used to draw right line junctions. Default:junction_char.
left_junction_charSingle character string used to draw left line junctions. Default:junction_char.
top_right_junction_charSingle character string used to draw top-right line junctions. Default:junction_char.
top_left_junction_charSingle character string used to draw top-left line junctions. Default:junction_char.
bottom_right_junction_charSingle character string used to draw bottom-right line junctions. Default:junction_char.
bottom_left_junction_charSingle character string used to draw bottom-left line junctions. Default:junction_char.
min_table_widthNumber of characters used for the minimum total table width.
max_table_widthNumber of characters used for the maximum total table width.
max_widthNumber of characters used for maximum width of a column.
min_widthNumber of characters used for minimum width of a column.
use_header_widthA Boolean option (must beTrue orFalse). Controls whether the width of the header is used for computing column width. Default:True.
break_on_hyphensWhether long lines are wrapped on hyphens. Default:True.

You can set the style options to your own settings in two ways:

Setting style options for the long term

If you want to print your table with a different style several times, you can set youroption for the long term just by changing the appropriate attributes. If you never wantyour tables to have borders you can do this:

table.border=Falseprint(table)print(table)print(table)

Neither of the 3 tables printed by this will have borders, even if you do things likeadd extra rows in between them. The lack of borders will last until you do:

table.border=True

to turn them on again. This sort of long-term setting is exactly howset_style works.set_style just sets a bunch of attributes to pre-set values for you.

Note that if you know what style options you want at the moment you are creating yourtable, you can specify them using keyword arguments to the constructor. For example, thefollowing two code blocks are equivalent:

table=PrettyTable()table.border=Falsetable.header=Falsetable.padding_width=5table=PrettyTable(border=False,header=False,padding_width=5)

Changing style options just once

If you don't want to make long-term style changes by changing an attribute like in theprevious section, you can make changes that last for just oneget_string by givingthose methods keyword arguments. To print two "normal" tables with one borderless tablebetween them, you could do this:

print(table)print(table.get_string(border=False))print(table)

Changing the appearance of your table - withcolors!

PrettyTable has the functionality of printing your table with ANSI color codes. Thisincludes support for most Windows versions throughColorama. To get started, import theColorTableclass instead ofPrettyTable.

-from prettytable import PrettyTable+from prettytable.colortable import ColorTable

TheColorTable class can be used the same asPrettyTable, but it adds an extraproperty. You can now specify a customtheme that will format your table with colors.

fromprettytable.colortableimportColorTable,Themestable=ColorTable(theme=Themes.OCEAN)print(table)

Creating a custom theme

TheTheme class allows you to customize both the characters and colors used in yourtable.

ArgumentDescription
default_colorThe color to use as default
vertical_char,horizontal_char, andjunction_charThe characters used for creating the outline of the table
vertical_color,horizontal_color, andjunction_colorThe colors used to style each character.

Note: Colors are formatted with theTheme.format_code(s: str) function. Itaccepts a string. If the string starts with an escape code (like\x1b) then it willreturn the given string. If the string is just whitespace, it will return"". If thestring is a number (like"34"), it will automatically format it into an escape code.I recommend you look into the source code for more information.

Displaying your table in JSON

PrettyTable will also print your tables in JSON, as a list of fields and an array ofrows. Just like in ASCII form, you can actually get a string representation - just useget_json_string().

Displaying your table in MediaWiki markup

PrettyTable can also print your tables in MediaWiki table markup, making it easy toformat tables for wikis. Similar to the ASCII format, you can get a stringrepresentation usingget_mediawiki_string().

Displaying your table in HTML form

PrettyTable will also print your tables in HTML form, as<table>s. Just like in ASCIIform, you can actually get a string representation - just useget_html_string(). HTMLprinting supports thefields,start,end,sortby andreversesort arguments inexactly the same way as ASCII printing.

Styling HTML tables

By default, PrettyTable outputs HTML for "vanilla" tables. The HTML code is quitesimple. It looks like this:

<table><thead><tr><th>City name</th><th>Area</th><th>Population</th><th>Annual Rainfall</th></tr></thead><tbody><tr><td>Adelaide</td><td>1295</td><td>1158259</td><td>600.5</td></tr><tr><td>Brisbane</td><td>5905</td><td>1857594</td><td>1146.4</td>      ...</tr></tbody></table>

If you like, you can ask PrettyTable to do its best to mimic the style options that yourtable has set using inline CSS. This is done by giving aformat=True keyword argumenttoget_html_string method. Note that if youalways want to print formatted HTML youcan do:

table.format=True

and the setting will persist until you turn it off.

Just like with ASCII tables, if you want to change the table's style for just oneget_html_string you can pass those methods' keyword arguments - exactly likeprintandget_string.

Setting HTML attributes

You can provide a dictionary of HTML attribute name/value pairs to theget_html_stringmethod using theattributes keyword argument. This lets you specify common HTMLattributes likeid andclass that can be used for linking to your tables orcustomising their appearance using CSS. For example:

print(table.get_html_string(attributes={"id":"my_table","class":"red_table"}))

will print:

<tableid="my_table"class="red_table"><thead><tr><th>City name</th><th>Area</th><th>Population</th><th>Annual Rainfall</th></tr></thead><tbody><tr>      ... ... ...</tr></tbody></table>

Setting HTML escaping

By default, PrettyTable will escape the data contained in the header and data fieldswhen sending output to HTML. This can be disabled by setting theescape_header andescape_data to false. For example:

print(table.get_html_string(escape_header=False,escape_data=False))

Miscellaneous things

Copying a table

You can call thecopy method on a PrettyTable object without arguments to return anidentical independent copy of the table.

If you want a copy of a PrettyTable object with just a subset of the rows, you can uselist slicing notation:

new_table=old_table[0:5]

Contributing

After editing files, use theBlack linter to auto-formatchanged lines.

python -m pip install blackblack prettytable*.py

[8]ページ先頭

©2009-2025 Movatter.jp