0

什么是最好的写入我正在尝试的文本文件

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

这样它就会考虑第一列中最长的内容长度,并相应地放置第二列!

4

2 回答 2

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

于 2014-10-15T21:45:45.820 回答
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)
于 2014-10-15T22:27:29.627 回答