0

I am coding a shop program that uses GTIN-8 numbers to purchase products, add the purchased products to a receipt, give the user the receipt and also when the admin password is entered, work out and display the stock levels of the products and their re-order levels.

I cant figure out a way to replace the stock levels of a product within the file with a variable that stores the stock of that product with the recently purchased amount of it taken away.

The ordered products GTIN-8 number is stored in a variable called "GTIN" (the GTIN-8 number is valid as it gets validated before hand) and the quantity of that product is stored in a variable called "Quantity".

This is the code section so far:

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

The stock files contents (in "") are so far:

"12345670,700,

57954363,700,

09499997,700,

79797979,700,

00000000,700,

11111115,700,"

12345670 - (the first number) being the GTIN-8 number of the product

700 - (the second number) being its stock level

I would love it if someone could please tell and show me how I could replace the stock files quantity with the new_stock variable. So if the quantity was 5, the stock file would end up as: "12345670,695,". Thanks!

B.Wheaton
  • 25
  • 3
  • Maybe this can help: http://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python – Giuseppe Cammarota Apr 04 '16 at 15:03
  • I recommend to replace the left hand side of the split statement to several variables (tuple unpacking) like *gtin, quantity". Not only are the following lines easier to read then, you also immediately get an exception if the number of separators is different from what you expect. – guidot Apr 04 '16 at 15:04

1 Answers1

0

This is a way of getting what you want:

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

The format method takes a template string (a string containing one or more sets of {}) and replaces each of those {} with a variable that you provide as an argument. It'll automatically handle converting your arguments to strings if they aren't already strings.

ArtOfWarfare
  • 20,617
  • 19
  • 137
  • 193
  • Thanks, it works until you start using multiple lines in the stock file with new stocks, but still thanks anyways. – B.Wheaton Apr 14 '16 at 18:12