我正在制作一个以有序方式显示产品清单的代码,用户可以输入GTIN-8代码并选择他们希望“购买”的金额。因此,当用户输入GTIN-8代码时,FullLine应该是产品列表中的产品说明等并显示金额。但是,金额出现在我不想要的新线上。我试过在产品清单之后,在它之前和之后放置换行符,但它不会保持在同一行。 下面是代码:Python - 保持文本文件在一行?
nl="\n"
Products=open("Productsfile.txt","w")
Products.write(nl+"23456945, Thorntons Chocolate Box, £10.00")
Products.write(nl+"12376988, Cadburys Easter Egg, £15.00")
Products.write(nl+"76543111, Galaxy Bar, £1.00")
Products.write(nl+"92674769, Cadury Oreo Bar, £1.00")
Products.write(nl+"43125999, Thorntons Continental Box, £12.00")
Products.close()
Products=open("Productsfile.txt","r")
print(Products.read())
Receipt=open("ReceiptFile.txt","w")
Receipt.write("Here are your purchases: \n")
Receipt.close()
print("Please enter the GTIN-8 Codes of the products you want and how many")
IfFinished=""
while IfFinished != "Yes":
ProductsWanted=input("Please enter the GTIN-8 Code of the product: ")
AmountOfProducts=input("How many do you want? ")
with open("Productsfile.txt") as f:
for line in f:
if ProductsWanted in line:
FullLine=(line +"Amount: " +AmountOfProducts)
print(FullLine)
Receipt=open("ReceiptFile.txt","a")
Receipt.write(str(FullLine))
Receipt.close()
所以运行的时候,我得到的,例如:
23456945, Thorntons Chocolate Box, £10.00
Amount: 2
但是我想在同一行
尝试使用'line.strip()'t o返回没有任何前导或尾随空白的新字符串,包括换行符。 – jonrsharpe