python:从文件(从prettytable创建)中读取一个表,并使用mantain空格

2024-04-30 03:57:57 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下几点文件.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.0textbuffer(类似于print)显示每一行:

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      |
+-----------+------+------------+-----------------+

有什么建议如何使它看起来更漂亮(像第一张桌子)?你知道吗

提前谢谢!你知道吗


Tags: 文件nameselftxtcityareafileend
1条回答
网友
1楼 · 发布于 2024-04-30 03:57:57

您可能需要按如下方式格式化字符串:

Python: Format output string, right alignment 输出中的

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

在输出中,可以指定with(或根据输入的长度获取)。你知道吗

我自己还没有使用过gtk2.0,但也许它会有所帮助https://docs.python.org/3/library/string.html#formatstrings

相关问题 更多 >