read csv error question

MRAB google at mrabarnett.plus.com
Mon Feb 23 18:43:05 EST 2009


Vincent Davis wrote:
> I am trying to read a csv file from excel on a mac. I get the following 
> error.
> SystemExit: file some.csv, line 1: new-line character seen in unquoted 
> field - do you need to open the file in universal-newline mode?
> I was using the example code
> import csv, sys
> 
> reader = csv.reader(open('/Volumes/vincentdavis 
> 2/match/data/matchdata2008.csv', "rb"))
> try:
>     for row in reader:
>         print row
> except csv.Error, e:
>     sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
> 
> I think this has to do with the end of line character but I am unsure 
> how to fix it. I don't what to change the actual csv file I would like 
> to fix the code.
> 
FYI, Mac line endings are carriage-return '\r', Linux line endings are 
linefeed '\n', and Windows endings are _both_ '\r\n'.

Try:

     reader = csv.reader(open('/Volumes/vincentdavis 
2/match/data/matchdata2008.csv', "U")) # or "rU"

This will open the file for reading with "universal" line ending
support, which will accept any kind of these line endings. (Opening it
in text mode "r" should also work, assuming that the .csv file does
indeed have the correct line endings for that platform.)



More information about the Python-list mailing list