[英]Python - Keeping text file in one line?
我正在編寫一個以有序方式顯示產品列表的代碼,用戶可以輸入GTIN-8代碼並選擇他們希望“購買”的數量。 因此,當用戶輸入GTIN-8代碼時,FullLine應該是產品說明等,該說明位於產品列表中並顯示金額。 但是,該金額顯示在我不希望的新行上。 我嘗試將換行符放在產品列表之后,之前和之下,但不會停留在同一行上。 這是代碼:
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
但是我希望金額在同一行
使用rstrip方法,更改FullLine=(line +"Amount: " +AmountOfProducts)
到FullLine=(line.rstrip() +"Amount: " +AmountOfProducts)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.