0

I know that it is not possible to write to a specific cell in a csv file , but in my code I have been trying to change a value if a command is met. So if the user enters a number higher than the target stock ( the suitable stock amount , last column) then it will subtract the entered number from the current stock ( 3rd column) and then write back the new stock.The problem with my code that it writes over everything :

before writing to csv :

86947367,banana,100,40
78364721,apple,50,20
35619833,orange,20,30
84716491,sweets,200,90
46389121,chicken,5,10

after writing to csv:

86947367,banana,2,40

As you can see it overwrites the whole stock file with the row that the stock has changed in.

my current code :

import csv

file=open("stock.csv")
stockfile= csv.reader(file)
for line in stockfile:
    if GTIN in line:
        currentstock= line[2]
        targetstock = line[3]
        newstock = (int(currentstock) - int(Quantity))
        targetstock = str(targetstock)
        newstock = str(newstock)

        if newstock < targetstock :


            with open('stock.csv', 'r') as infile:
                oldata = csv.reader(infile)
                for row in oldata:
                    if GTIN == row[0]:
                        newstock=int(row[2]) - int(Quantity)
                        row[2] = newstock
                        print(row)
                        with open("output.csv","w") as outfile:
                            newdata = csv.writer(outfile)
                            newdata.writerow(row)
        else:
            print("lel")

All help appreciated.

JJ.123
  • 25
  • 2
  • 2
    maybe you should read the old file into a pandas dataframe (eg: old_file = pd.read_csv(path), make the changes in the DataFrame columns and write the modified file back to CSV (eg old_file.to_csv(path)) – Siraj S. Nov 08 '16 at 19:42

1 Answers1

0

Most of my answer stems from this one. Piggybacking off of that, I would recommend using the fileinput module. You can print() whatever you want to write the file as you iterate over the lines. I am having trouble completely understanding your problem, but I think this code snippet gets most of the work done.

import csv
import fileinput

# setting some things for what I think applies to your example
GTIN = "86947367"
Quantity = "98"

# set inplace=False if you do not want to modify the file inplace
# for example to debug you can set it to false and look at the output
with fileinput.FileInput(files=['stock.csv'], inplace=True, backup='.bak') as input:
    for line in input:
        if GTIN in line:
            # a little workaround to parse a string as csv
            csv_elements = [i for i in csv.reader([line])][0]
            new_stock = int(csv_elements[2]) - int(Quantity)
            target_stock = int(csv_elements[3])
            # check for your condition here
            if new_stock < target_stock:
                # update appropriate element in csv_elements
                csv_elements[2] = str(new_stock)
            # join everything back together with commas
            print(",".join(csv_elements))
        else:
            # if it's not the stock to update, just print the same line
            # set end to empty string to avoid extra newlines
            print(line, end="")

The CSV workaround is at the very bottom - Python CSV

Community
  • 1
  • 1
gregbert
  • 446
  • 2
  • 5