Python - 将文本文件保留在一行中?

标签 python lines

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

关于Python - 将文本文件保留在一行中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43274500/

相关文章:

python - 对于不运行 PSET6 DNA CS50x 的循环

vim - 如何在当前行之后加入上面的行?

php - 在 Windows 上用 PHP 计算文件行数

linux - 如何在第一个字段上操作数学数据并分配变量 linux

random - 从带有 awk 代码的文件中随机选择 3000 行

Python 配对点列表,如何沿线查找点

python - 在 NumPy 数组中获取唯一行时保留顺序

python - 比 numpy.where 更快的替代品?

python - 纯 python ssh

Python np.sqrt(x-a)*np.heaviside(x,a)