4.2.1.6. Markdown¶
MarkdownTableWriter
class can write a table to the stream
with Markdown table format from a data matrix.
- Sample Code:
- Write a Markdown table¶
from pytablewriter import MarkdownTableWriter def main(): writer = MarkdownTableWriter( table_name="example_table", headers=["int", "float", "str", "bool", "mix", "time"], value_matrix=[ [0, 0.1, "hoge", True, 0, "2017-01-01 03:04:05+0900"], [2, "-2.23", "foo", False, None, "2017-12-23 45:01:23+0900"], [3, 0, "bar", "true", "inf", "2017-03-03 33:44:55+0900"], [-10, -9.9, "", "FALSE", "nan", "2017-01-01 00:00:00+0900"], ], ) writer.write_table() if __name__ == "__main__": main()
- Output:
# example_table |int|float|str |bool | mix | time | |--:|----:|----|-----|-------:|------------------------| | 0| 0.10|hoge|True | 0|2017-01-01 03:04:05+0900| | 2|-2.23|foo |False| |2017-12-23 12:34:51+0900| | 3| 0.00|bar |True |Infinity|2017-03-03 22:44:55+0900| |-10|-9.90| |False| NaN|2017-01-01 00:00:00+0900|
- Rendering Result:
Rendered markdown at GitHub¶
4.2.1.6.1. Markdown with margins¶
- Sample Code:
- Write a Markdown table with margins¶
from pytablewriter import MarkdownTableWriter def main(): writer = MarkdownTableWriter( table_name="write a table with margins", headers=["int", "float", "str", "bool", "mix", "time"], value_matrix=[ [0, 0.1, "hoge", True, 0, "2017-01-01 03:04:05+0900"], [2, "-2.23", "foo", False, None, "2017-12-23 45:01:23+0900"], [3, 0, "bar", "true", "inf", "2017-03-03 33:44:55+0900"], [-10, -9.9, "", "FALSE", "nan", "2017-01-01 00:00:00+0900"], ], margin=1 # add a whitespace for both sides of each cell ) writer.write_table() if __name__ == "__main__": main()
- Output:
# write a table with margins | int | float | str | bool | mix | time | | --: | ----: | ---- | ----- | -------: | ------------------------ | | 0 | 0.10 | hoge | True | 0 | 2017-01-01 03:04:05+0900 | | 2 | -2.23 | foo | False | | 2017-12-23 12:34:51+0900 | | 3 | 0.00 | bar | True | Infinity | 2017-03-03 22:44:55+0900 | | -10 | -9.90 | | False | NaN | 2017-01-01 00:00:00+0900 |
margin
attribute can be available for all of the text format writer classes.
4.2.1.6.2. GitHub flavored Markdown (GFM)¶
If you set flavor
keyword argument of MarkdownTableWriter
class to "github"
or "gfm"
, the writer will output markdown tables with GitHub flavor.
GFM can apply some additional styles to tables such as fg_color
(text color).
- Sample Code:
- Write a Markdown table with GitHub flavor¶
from pytablewriter import MarkdownTableWriter from pytablewriter.style import Style writer = MarkdownTableWriter( column_styles=[ Style(fg_color="red"), Style(fg_color="green", decoration_line="underline"), ], headers=["A", "B"], value_matrix=[ ["abc", 1], ["efg", 2], ], margin=1, flavor="github", enable_ansi_escape=False, ) writer.write_table()
Rendered results can be found at here