Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use csv.Sniffer for 2 different CSV-types?

I want to read 2 different types of CSV-files:

  • one with a ',' as delimiter
  • one with a ';' as delimiter

I tried to check which delimiter I'm using by doing:

dialect = csv.Sniffer().sniff(csvfile, [',', ';'])  
data = csv.reader(csvfile, dialect)

but then I get the TypeError : expected string or buffer.

If I do this, it works, but then I don't know when to use what delimiter.

data = csv.reader(csvfile, delimiter = ",")  
data = csv.reader(csvfile, delimiter = ";")

Can someone help me please?

like image 896
tdhulster Avatar asked Feb 26 '13 16:02

tdhulster


1 Answers

Sniffer expects a sample string, not a file. All you should need to do is:

dialect = csv.Sniffer().sniff(csvfile.readline(), [',',';'])
csvfile.seek(0)  
data = csv.reader(csvfile, dialect)

The seek is important, because you are moving your current position in the file with the readline command, and you need to reset back to the beginning of the file. Otherwise you lose data.

like image 193
Spencer Rathbun Avatar answered Sep 26 '22 00:09

Spencer Rathbun