如何替换文件中分割线的一部分?

时间:2016-04-04 14:47:59

标签: python python-2.7

我正在编写一个商店程序,使用GTIN-8号码购买产品,将购买的产品添加到收据中,给用户收据,以及输入管理员密码时,计算并显示库存水平。产品及其重新订购水平。

我无法找到一种方法来替换文件中产品的库存水平,并使用一个变量来存储该产品的库存以及最近购买的产品的数量。

订购的产品GTIN-8编号存储在名为" GTIN"的变量中。 (GTIN-8号码在事先经过验证时有效),该产品的数量存储在名为" Quantity"的变量中。

到目前为止,这是代码部分:

with open("stock.txt", "r") as stock:#opens stock file
    for line in stock:
        line2 = line.split(",")#goes through the lines of the stock file and finds the product that matches the purchased product
        if line2[0] == GTIN:
            stock_level = int(line2[1])
            new_stock = stock_level - int(quantity)#Creates the new stock amount by taking away the recently purchased amount by the current stock
            with open("stock.txt", "a") as stock:
                      #replace line2[1] with the new_stock variable

库存文件内容("")到目前为止:

" 12345670,700,

57954363,700,

09499997,700,

79797979,700,

00000000,700,

11111115,700,"

12345670 - (第一个数字)是产品的GTIN-8编号

700 - (第二个数字)是其库存水平

如果有人可以告诉并告诉我如何用new_stock变量替换库存文件数量,我会很高兴。因此,如果数量为5,则库存文件将最终为:" 12345670,695,"。谢谢!

1 个答案:

答案 0 :(得分:0)

这是获得你想要的东西的方式:

stock.write('{},{}'.format(line2[0], new_stock))

format方法采用模板字符串(包含一组或多组{}的字符串),并将每个{}替换为您提供的变量作为参数。如果它们不是字符串,它会自动处理将参数转换为字符串。

相关问题