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>With only one column, I wonder why you made it as a <code>result.csv</code>. If it is not going to have any more columns, a simple file read operation would suffice. Along with converting the data from <code>result.csv</code> to dictionary will help in quick run as well.</p>

<pre><code>result_file = "result.csv"
sample_file = "sample.csv"

with open(result_file) as fp:
    result_data = fp.read()
    result_dict = dict.fromkeys(result_data.split("\n"))
    """
    You can change the above logic, in case you have very few fields on csv like this:
    result_data = fp.readlines()
    result_dict = {}
    for result in result_data:
        key, other_field = result.split(",", 1)
        result_dict[key] = other_field.strip()
    """

#Since sample.csv is a real csv, using csv reader and writer
with open(sample_file, "rb") as fp:
    sample_data = csv.reader(fp)
    output_data = []
    for data in sample_data:
        output_data.append("%s,%d" % (data, data[0] in result_dict))

with open(sample_file, "wb") as fp:
    data_writer = csv.writer(fp)
    data_writer.writerows(output_data)
</code></pre>

python append