Quantcast
Viewing all articles
Browse latest Browse all 2

Answer by Laurent LAPORTE for Writing to a mac csv not working using python file writter

The end delimiters of the two files are different.

  • The .csv file probably has Windows end of line: "\r\n",
  • The .txt file probably has Posix end of line: "\n".

So, in binary mode, lines always differ.

You ought to read the two files in text mode, like this:

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)

You'll get:

set([u'M11543TH4258\n', u'M11509TD9937\n', u'M11543TH4292\n', u'M11435TDS144\n'])

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

to drop the newlines

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)

Viewing all articles
Browse latest Browse all 2

Trending Articles