title: How to write back changed CSV file
body: <p>Before flagging as duplicate, I have read 5 other topics similar to this but did not seem to work.</p>
  
  <p>I have been able to change a value in a CSV file. However, I can not figure out how to write back the whole file. I have only been able to write back the changed line.</p>
  
  <p>Code:</p>
  
  <pre><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)
                      line[2]= int(newstock)
                      print(line)
                      with open("output.csv","w") as outfile:
                          newdata = csv.writer(outfile)
                          newdata.writerow(line)
                          if newstock&lt;targetstock:
                              print("stock needs updating...please wait a moment")
                          else:
                              print("stock is fine")
  </code></pre>
  
  <p>Stock.csv :</p>
  
  <pre><code>86947367,banana,100,40
  78364721,apple,50,20
  35619833,orange,20,30
  84716491,sweets,200,90
  46389121,chicken,40,10
  </code></pre>
  
  <p>output.CSV: ( only writes back the changed line and not the rest of the file)</p>
  
  <pre><code>86947367    banana  1   40
  </code></pre>
  
  <p>I want:</p>
  
  <pre><code>    86947367,banana,1,40
      78364721,apple,50,20
      35619833,orange,20,30
      84716491,sweets,200,90
      46389121,chicken,40,10
  </code></pre>
  
  <p>thank you.</p>