Closed fedderw closed 2 years ago
You can use writer.dump
:
So adding to the example at https://pytablewriter.readthedocs.io/en/latest/pages/examples/table_format/text/markdown.html:
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()
writer.dump("my_markdown.md")
if __name__ == "__main__":
main()
And then my_markdown.md
contains:
# 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 45:01:23+0900|
| 3| 0.00|bar |True |Infinity|2017-03-03 33:44:55+0900|
|-10|-9.90| |False| NaN|2017-01-01 00:00:00+0900|
Oh ok, awesome, thanks! Can I write any string to the writer object?
Yes, the first parameter to writer.dump
can be whatever filename you like (or an output stream):
output – The value must either an output stream or a path to an output file.
@fedderw Thank you for your feedback, I had added a link to an example usage to the README: https://github.com/thombashi/pytablewriter#write-a-markdown-table-to-a-stream-or-a-file
@hugovk Thank you for your answer.
Is it possible to use dump
to append the table to an existing file? I think at the moment it is overwriting by default. Thanks
@PabloPeso This is possible with code like the following:
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()
with open("my_markdown.md", "a") as f:
writer.dump(f)
if __name__ == "__main__":
main()
It's not obvious to all programmers (me) how to get the output from the writer object to, say, a markdown file.