【问题标题】:Python - Keeping text file in one line?Python - 将文本文件保存在一行中?
【发布时间】:2017-04-07 09:27:13
【问题描述】:

我正在制作一个以有序方式显示产品列表的代码,用户可以输入 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

但我希望金额在同一行

【问题讨论】:

  • 尝试使用line.strip()返回一个新字符串,不带任何前导或尾随空格,包括换行符。

标签: python lines


【解决方案1】:

使用rstrip方法,更改FullLine=(line +"Amount: " +AmountOfProducts)

FullLine=(line.rstrip() +"Amount: " +AmountOfProducts)

【讨论】:

  • 嗨@Chloe,如果这个或任何答案解决了您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
猜你喜欢
  • 2022-10-15
  • 2018-04-24
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 2019-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多