Writing to a file after parsing
<p>I have written a small python code where it will read a sample csv file and copy its first column to a temp csv file. Now when I try to compare that temporary file with another text file and try to write result to another file called result file, The file is created but with empty content.</p>

<p>But when i tested it in chunks, It is working fine</p>

<pre><code>import csv
f = open("sample.csv", "r")
reader = csv.reader(f)

data = open("temp1.csv", "w")
w = csv.writer(data)
for row in reader:
    my_row = []
    my_row.append(row[0])
    w.writerow(my_row)

with open('temp1.csv', 'r') as file1:
    with open('serialNumber.txt', 'r') as file2:
        same = set(file1).intersection(file2)

with open('result.txt', 'w') as file_out:
    for line in same:
        file_out.write(line)
        print line
</code></pre>

<p>sample.csv</p>

<blockquote>
  <p>M11435TDS144,STB#1,Router#1</p>
  
  <p>M11543TH4292,STB#2,Router#1</p>
  
  <p>M11509TD9937,STB#3,Router#1 </p>
  
  <p>M11543TH4258,STB#4,Router#1</p>
</blockquote>

<p>serialNumber.txt</p>

<blockquote>
  <p>G1A114042400571</p>
  
  <p>M11543TH4258</p>
  
  <p>M11251TH1230</p>
  
  <p>M11435TDS144</p>
  
  <p>M11543TH4292</p>
  
  <p>M11509TD9937</p>
</blockquote>

<p>You should close the output file (<code>temp1.csv</code>) before you can read data from it.</p>

<pre><code>import csv
f = open("sample.csv", "r")
reader = csv.reader(f)

data = open("temp1.csv", "w")
w = csv.writer(data)
for row in reader:
    my_row = []
    my_row.append(row[0])
    w.writerow(my_row)
data.close()  # &lt;--- Should close it before reading it in the same program !!

with open('temp1.csv', 'r') as file1:
    with open('serialNumber.txt', 'r') as file2:
        same = set(file1).intersection(file2)

with open('result.txt', 'w') as file_out:
    for line in same:
        file_out.write(line)
        print line
</code></pre>

python file-writing