Python file matching and appending
<p>This is one file <code>result.csv</code>:</p>

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

<p>This is another file <code>sample.csv</code>:</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>Can I write a Python program to compare both the files and if line in <code>result.csv</code> matches with the first word in the line in <code>sample.csv</code>, then append 1 else append 0 at every line in <code>sample.csv</code>?</p>

<p>The solution using <code>csv.reader</code> and <code>csv.writer</code> (<code>csv</code> module):</p>

<pre><code>import csv

newLines = []
# change the file path to the actual one
with open('./data/result.csv', newline='\n') as csvfile:
    data = csv.reader(csvfile)
    items = [''.join(line) for line in data]

with open('./data/sample.csv', newline='\n') as csvfile:
    data = list(csv.reader(csvfile))
    for line in data:
        line.append(1 if line[0] in items else 0)
        newLines.append(line)

with open('./data/sample.csv', 'w', newline='\n') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(newLines)
</code></pre>

<p>The <code>sample.csv</code> contents:</p>

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

python append