how to .writerow() to only 1 row in csv file ?
<p>guys 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.</p>

<p>current code :</p>

<pre><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 &lt; 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]])
</code></pre>

<p>output in file ( it changes all numbers in 3rd column):</p>

<pre><code>86947367,banana,1,40
78364721,apple,1,20
35619833,orange,1,30
84716491,sweets,1,90
46389121,chicken,1,10
</code></pre>

<p>How can I only chnage the row with the GTIN the user enters ?</p>

<p>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 <code>stock.txt</code>. Just read it line by line then write line by line to an output file:</p>

<pre><code>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)
</code></pre>

<p>Edit: here it is with <code>csv</code> module instead. This makes it a little more straightforward because the <code>csv</code> 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. </p>

<pre><code>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)
</code></pre>

<p>Also you shouldn't really <code>import</code> anything in the middle of the code like that. Imports generally go at the top of your file. </p>

python file python-3.x csv