简体   繁体   English

Python:如何插入标签页并设置文本文件格式

[英]Python: How to insert tab and format text file

Bringing in a text file that is formatted like below: 导入一个格式如下的文本文件:

hammer#9.95
saw#20.15
shovel#35.40

I need to bring it into python and format it so that it is in line with an existing snippet of code: 我需要将其放入python并对其进行格式化,以使其与现有的代码片段一致:

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

The goal is for the text file to be in line with existing headers like so: 目标是使文本文件与现有的标头保持一致,如下所示:

Item   Cost
hammer $9.95
saw    $20.15
shovel $35.4

I can bring in the text file into Python and get replace the # sign with a $ sign: 我可以将文本文件引入Python并用$符号替换#符号:

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

Which gives me this output: 这给了我这个输出:

hammer$9.95
saw$20.15
shovel$35.40

but I'm having trouble with the formatting aspect. 但我在格式化方面遇到麻烦。 Any suggestions? 有什么建议么?

You can do something like this: 您可以执行以下操作:

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

only problem is that it'll look ugly if you have a longer word than hammer. 唯一的问题是,如果您说的话比锤子长,看起来会很难看。 I suggest finding the largest word in your list first, then using that as the limiter for the {:<6}. 我建议首先在列表中找到最大的单词,然后将其用作{:<6}的限制符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用python将制表符限制的文本文件插入sql数据库? - how to insert tab limited text file into sql database using python? 如何在Python中将tab插入输出到文件中? - How to insert tab into the output to a file in Python? 如何使用 Python 检索具有制表符格式的文件中的值? - How to retrieve a value in a file with tab format using Python? 如何在 Python 中将制表符分隔、管道分隔转换为 CSV 文件格式 - How to convert tab separated, pipe separated to CSV file format in Python 如何在python中将json文本文件插入sqlite? - How to insert a json text file to a sqlite in python? 在python中格式化文本文件 - Format Text File in python 在python中以制表符分隔的格式拆分文本,将其添加到列表中并将其写入文件中……是否有更好的方法? - Splitting text in tab delimited format in python, adding it to list and writing it to a file… is there a better way? 通过python检查标题将行文本文件转换为制表符分隔格式 - Transform line by line text file into tab delimited format by checking header by python 如何使用python将制表符分隔的文本文件转换为JSON - How to convert tab delimited text file to JSON with python 如何使用 Python 将文本文件复制并粘贴到指定的 Excel TAB 中? - How to copy and paste text file into a specified Excel TAB using Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM