我正在编写一个商店程序,使用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,
000000000,700,
11111115700,“
12345670 -(第一个数字)是产品的GTIN-8编号
700 -(第二个数字)是其库存水平
如果有人能告诉我并展示如何用new_stock变量替换库存文件数量,我会很高兴。因此,如果数量是5,那么库存文件将结束为:"12345670,695,“。谢谢!
发布于 2016-04-04 22:57:31
这是一种获得你想要的东西的方式:
stock.write('{},{}'.format(line2[0], new_stock))format方法接受一个模板字符串(包含一组或多组{}的字符串),并用您作为参数提供的变量替换这些{}中的每一个。如果你的参数不是字符串,它会自动将它们转换成字符串。
https://stackoverflow.com/questions/36405898
复制相似问题