Python:如何插入选项卡和格式化文本文件

时间:2018-04-27 16:06:07

标签: python split format

引入格式如下的文本文件:

hammer#9.95
saw#20.15
shovel#35.40

我需要将它带入python并对其进行格式化,以使其与现有的代码片段保持一致:

# display header line for items list print('{0: <10}'.format('Item'), '{0: >17}'.format('Cost'), sep = '' )

目标是使文本文件与现有标题一致,如下所示:

Item   Cost
hammer $9.95
saw    $20.15
shovel $35.4

我可以将文本文件引入Python并使用$ sign替换#符号:

file = open('Invoice.txt', 'r')
file_contents = file.read()
new_file_contents = file_contents.replace('#', '$')

这给了我这个输出:

hammer$9.95
saw$20.15
shovel$35.40

但我在格式化方面遇到了麻烦。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可以这样做:

with open(file,'rt',encoding='utf-8') as infile:
    for line in infile:
        print("{:<6} {}".format(line.strip().split('#')[0],"$"+line.strip().split("#")[1]))

唯一的问题是,如果你的词比锤子更长,它看起来会很难看。我建议先找到列表中最大的单词,然后将其用作{:&lt; 6}的限制器。