Writing to a mac csv not working using python file writter
<p>I have a python code where it compares two files and returns the common lines and writes them to a result file. I am using a MAC machine.</p>

<p>script.py</p>

<pre><code>with open('temp1.csv', 'r') as file1:
    with open('serialnumbers.txt', 'r') as file2:
        same = set(file1).intersection(file2)
        print same

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

<p>temp1.csv</p>

<pre><code>M11435TDS144
M11543TH4292
SN005
M11509TD9937
M11543TH4258
SN005
SN006
SN007
</code></pre>

<p>serialnumbers.txt</p>

<pre><code>G1A114042400571
M11251TH1230
M11543TH4258
M11435TDS144
M11543TH4292
M11509TD9937
</code></pre>

<p>The output of the above script on mac is </p>

<blockquote>
  <p>set([])</p>
</blockquote>

<p>If I run the same script on windows it is working fine. I found out that this is a csv problem on mac. How can I resolve this issue?</p>

<p>The end delimiters of the two files are different.</p>

<ul>
<li>The .csv file probably has Windows end of line: "\r\n",</li>
<li>The .txt file probably has Posix end of line: "\n".</li>
</ul>

<p>So, in binary mode, lines always differ.</p>

<p>You ought to read the two files in text mode, like this:</p>

<pre><code>import io

with io.open('temp1.csv', 'r') as file1:
    with io.open('serialnumbers.txt', 'r') as file2:
        same = set(file1).intersection(file2)
        print(same)
</code></pre>

<p>You'll get:</p>

<pre><code>set([u'M11543TH4258\n', u'M11509TD9937\n', u'M11543TH4292\n', u'M11435TDS144\n'])
</code></pre>

<p>Also notice that CSV files are usually encoded using ISO-8859-1 or cp1252 encoding (legacy encoding from Windows).</p>

<h3>to drop the newlines</h3>

<pre><code>with io.open('temp1.csv', 'r') as file1:
    with io.open('serialnumbers.txt', 'r') as file2:
        same = set(line.strip() for line in file1).intersection(line.strip() for line in file2)
        print(same)
</code></pre>

python csv file-writing macbook