蟒蛇:从文件中读取(从prettytable创建)一个表,并保持空间

问题描述 投票:1回答:1

比方说,我有以下file.txt的

$ cat file.txt
+-----------+------+------------+-----------------+
| 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      |
| Sydney    | 2058 |  4336374   |      1214.8     |
| Melbourne | 1566 |  3806092   |      646.9      |
| Perth     | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

如果我尝试读这样的文件:

with open('file.txt') as fp:
    lines = fp.readlines()

然后,我尝试使用GTK2.0 textbuffer(类似于打印)来显示每行:

for eachline in lines:
    if idx == 0:
        self.textbuffer.delete(start, end)
        end = self.textbuffer.get_end_iter()
        self.textbuffer.set_text(eachline)
    else:
        self.textbuffer.insert(end, eachline)
        end = self.textbuffer.get_end_iter()

我得到以下的输出:

+-----------+------+------------+-----------------+
| 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      |
| Sydney    | 2058 |  4336374   |      1214.8     |
| Melbourne  | 1566 |  3806092   |      646.9      |
| Perth   | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

任何建议如何使它看起来更漂亮(像第一个表)?

提前致谢!

python pygtk prettytable
1个回答
2
投票

你可能想格式化字符串如下所示:

与输出等Python: Format output string, right alignment

for align, text in zip('<^>', ['left', 'center', 'right']): 
    '{0:{fill}{align}16}'.format(text, fill=align, align=align)

在输出中,你可以指定用(或获取基于您输入的长度)。

我还没有和GTK2.0自己的工作,但也许它会帮助https://docs.python.org/3/library/string.html#formatstrings

© www.soinside.com 2019 - 2024. All rights reserved.