【问题标题】:How do I save table from prettytable?如何从漂亮表中保存表格?
【发布时间】:2014-04-21 07:03:13
【问题描述】:

所以我正在使用库“prettytable”,并且能够在执行时打印出我的数据表。但是,我不知道如何将其保存到文件中。理想情况下,我希望将表格保存为 pdf,以便我可以将其用于我的报告。

这是来自漂亮网页本身的示例代码:

from prettytable import PrettyTable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
x.align["City name"] = "l" # Left align city names
x.padding_width = 1 # One space between column edges and contents (default)
x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
print x

【问题讨论】:

    标签: python numpy prettytable


    【解决方案1】:

    使用get_string()方法,文档字符串引用:

    def get_string(self, **kwargs):
    
        """Return string representation of table in current state.
           ...
        """
    

    例子:

    from prettytable import PrettyTable
    
    x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
    
    ...
    
    data = x.get_string()
    
    with open('test.txt', 'wb') as f:
        f.write(data)
    

    这将创建一个test.txt 文件,其中包含您的漂亮表格。

    希望对您有所帮助。

    【讨论】:

    • 我刚试过:data = x.get_string() numpy.savetxt(('data.txt'),data) 得到一个Indexerror: Tuple index out of range。
    • @user2869276 我已经包含了一个将数据写入文本文件的示例,请检查。
    • 这行得通!我试图将我的 prettytable.get_string() 保存在 .csv 文件中。唯一要添加的是----- with open('file.csv', 'wb', encoding='utf-8') as f: 希望有人觉得这有帮助:)
    【解决方案2】:

    @Komal Jaswani 您应该将 'wb' 模式更改为 'w' 模式。

    with open('test.txt', 'w') as f: f.write(data)

    【讨论】:

      【解决方案3】:

      使用 open and write 方法将数据保存到 test.txt 文件中。

      试试下面的代码,

      with open('test.txt', 'w') as f:
          f.write(data)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-04
        • 2014-02-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-07
        • 1970-01-01
        • 2021-01-14
        • 2019-08-13
        相关资源
        最近更新 更多