先说一下python中的.format格式化输出
python2.6开始,可以使用str.format进行轻松的格式化,
如上可以看到,对变量的处理简洁灵活,此外对数字的各种位数处理也很到位
{:<x}的语法表示左对齐(>为右对齐,^为居中),少于x位自动补齐(默认为空格补齐)
这里值得注意的是,x也可以作为变量代入:
示例:
data_filename = 'label.txt'
headers = 'picName', 'x1', 'y1','x2','y2','ClassName' # Column names.
# Read the data from file into a list-of-lists table.
with open(data_filename) as file:
datatable = [line.split() for line in file.read().splitlines()]
# Find the longest data value or header to be printed in each column.
widths = [max(len(value) for value in col)
for col in zip(*(datatable + [headers]))]
# Print heading followed by the data in datatable.
# (Uses '>' to right-justify the data in some columns.)
format_spec = '{:{widths[0]}} {:>{widths[1]}} {:>{widths[2]}}'
print(format_spec.format(*headers, widths=widths))
for fields in datatable:
print(format_spec.format(*fields, widths=widths))
参考网址:
python对齐输出关于python:将文本文件转换为表格格式