Python rewriting instead of appending
<p>I have two csv files result.csv and sample.csv.</p>

<p>result.csv</p>

<pre><code>M11251TH1230 
M11543TH4292 
M11435TDS144
</code></pre>

<p>sample.csv</p>

<pre><code>M11435TDS144,STB#1,Router#1 
M11543TH4292,STB#2,Router#1 
M11509TD9937,STB#3,Router#1
M11543TH4258,STB#4,Router#1
</code></pre>

<p>I have a python script which will compare both the files  if line in result.csv matches with the first word in the line in sample.csv, then append 1 else append 0 at every line in sample.csv</p>

<p>It should look like M11435TDS144,STB#1,Router#1,1 and M11543TH4258,STB#4,Router#1,0 since M11543TH4258 is not found in result.csv</p>

<p>script.py</p>

<pre><code>import csv
with open('result.csv', 'rb') as f:
    reader = csv.reader(f)
    result_list = []
    for row in reader:
        result_list.extend(row)


with open('sample.csv', 'rb') as f:
    reader = csv.reader(f)
    sample_list = []
    for row in reader:
        if row[0] in result_list:
            sample_list.append(row + [1])
        else:
            sample_list.append(row + [0])

with open('sample.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(sample_list)
</code></pre>

<p>sample output(sample.csv)if I run the script two times</p>

<pre><code>M11435TDS144,STB#1,Router#1,1,1 
M11543TH4292,STB#2,Router#1,1,1
M11509TD9937,STB#3,Router#1,0,0
M11543TH4258,STB#4,Router#1,0,0
</code></pre>

<p>Every time I run the script, 1's and 0's are being appended in a new column sample.csv. Is there any way every time I run the script, I can replace the appended column instead of increasing columns.</p>

<p>you write to the <code>sample.csv</code> and then you use it as input file, with the additional column. That's why you have more and more 1's and 0's in this file.
Regards, Grzegorz</p>

python csv fileappender