我所有的文本文件格式如下,将其引入Python:
hammer#9.95
saw#20.15
shovel#35.40
最终,我想开发一个动态查询,使我可以删除“#”符号并替换为“ $”符号,然后将文本文件中的值加起来/计算其中的项目数.我是通过反复试验得出的,但是处理文本文件中的更改并不是动态的:
# display header line for items list
print('{0: <10}'.format('Item'), '{0: >17}'.format('Cost'), sep = '' )
# add your remaining code below
with open('invoice.txt','rt') as infile:
for line in infile:
print("{:<21} {}".format(line.strip().split('#')[0],"$"+line.strip().split("#")[1]))
print(' ')
str1 = 'Total cost\t' +' ' + '$65.50'
print(str1)
str2 = 'Number of tools\t' + ' ' +'3'
print(str2)
有什么建议么?提前感谢您的阅读.
解决方法:
您可以通过以下方式进行操作: