写入具有适当对齐的文本文件

时间:2014-10-15 21:42:42

标签: python text file-io string-formatting rewriting

写入我正在尝试的文本文件的最佳效果是什么

>>> a = ['short', 'longline', 'verylongline']
>>> b = [123, 2347575, 8]
>>> ww = open("write_proper.txt", "w")
>>> for each in xrange(3):
...    ww.write("%s\t%s\n" % (a[each], b[each]))
...
>>> ww.close()

产生了输出:

short   123
longline    2347575
verylongline    8

有没有什么方法可以将内容间隔得恰到好处:

short           123
longline        2347575
verylongline    8

因此它考虑了第1列中最长的内容长度并且相应地放置了第2列!

2 个答案:

答案 0 :(得分:0)

如果您知道字段宽度先验,那么您可以在格式规范中包含字段宽度:

ww.write("%-12s\t%s\n" % (a[each], b[each]))

如果您希望数据对数据敏感,请尝试:

awidth = max(len(x) for x in a)
...
ww.write("%-*s\t%s\n" % (awidth, a[each], b[each]))

参考:https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

答案 1 :(得分:0)

更先进的解决方案:

a = ['short', 'longline', 'verylongline']
b = [123, 2347575, 8]

items = zip(a, b)
awidth = max(len(item) for item in a)
line_format = '{label:<{awidth}} {value}\n'

with open('write_proper.txt', 'w') as f:
    for label, value in items:
        line = line_format.format(**locals())
        f.write(line)