Reputation:
Currently in my code it changes the 3rd row but for all rows, I want it to only change the row with the entered GTIN
by the user.
Current code:
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))
currentstock = str(currentstock)
targetstock = str(targetstock)
newstock = str(newstock)
if newstock < targetstock :
import csv
reader = csv.reader(open('stock.csv',"r"))
new = csv.writer(open('out.csv',"w"))
for line in reader:
new.writerow([line[0], line[1], newstock , line[3]])
Output in file (it changes all numbers in 3rd column):
86947367,banana,1,40
78364721,apple,1,20
35619833,orange,1,30
84716491,sweets,1,90
46389121,chicken,1,10
How can I only change the row with the GTIN
the user enters?
Upvotes: 1
Views: 2124
Reputation: 856
I answered one of your other questions before you were using csvreader but it looks like it got deleted. But the principle is the same. As I stated in one of the comments, I don't think you should keep reopening/rereading stock.txt
. Just read it line by line then write line by line to an output file:
stock_number = input('Enter the stock number: ')
new_item = input('Enter item to add to above stock listing: ')
lines = []
with open('stock.txt', 'r') as infile:
for line in infile:
lines.append(line)
# can call this 'output.txt' if you don't want to overwrite original
with open('stock.txt', 'w') as outfile:
for line in lines:
if stock_number in line:
# strip newline, add new item, add newline
line = '{},{}\n'.format(line.strip(), new_item)
outfile.write(line)
Edit: here it is with csv
module instead. This makes it a little more straightforward because the csv
module gives you a list of strings for each line, then you can add to or modify them as desired. Then you can just write the list back line by line, without worrying about newlines or delimiters.
import csv
stock_number = input('Enter the stock number: ')
new_item = input('Enter item to add to above stock listing: ')
lines = []
with open('stock.txt', 'r') as infile:
for line in csv.reader(infile):
lines.append(line)
# change this to 'stock.txt' to overwrite original file
with open('output.txt', 'w') as outfile:
writer = csv.writer(outfile)
for line in lines:
if stock_number in line:
line.append(new_item)
writer.writerow(line)
Also you shouldn't really import
anything in the middle of the code like that. Imports generally go at the top of your file.
Upvotes: 0
Reputation: 60604
use the csv
module:
https://docs.python.org/3/library/csv.html
It has a csv.reader()
and csv.writer()
. Read the file into memory, iterate over it doing calcs/replacements, then write each row to a new list. Finally, generate a new data file to replace the old one.
Upvotes: 1