Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open the file in universal-newline mode using the CSV Django module

I am trying to access a model.filefield in Django to parse a CSV file in Python using the csv module. It's working on Windows, but on Mac it gave me this:

Exception Type: Error  Exception Value: new-line character seen in unquoted field - do you need to open the file in universal-newline mode? 

This is the code:

myfile = customerbulk.objects.all()[0].fileup  mydata = csv.reader(myfile)     for email,mobile,name,civilid in mydata:         print email,mobile,name,civilid 
like image 438
mohd Avatar asked Jul 17 '11 21:07

mohd


People also ask

Do you need to open the file in Universal newline mode?

While universal newlines are automatically enabled for import they are not for opening, where you have to specifically say open(..., "U") . This is open to debate, but here are a few reasons for this design: Compatibility. Programs which already do their own interpretation of \r\n in text files would break.

What does newline mean in Python csv?

It should always be safe to specify newline='' , since the csv module does its own newline handling. Since windows denote newline as \r\n , the python reads two new lines. First it reads the first line till before \r and creates a list from whatever data was before this character and then creates a new line.

What is the importance of newline used for opening of csv file?

Including the newline parameter allows the csv module to handle the line endings itself - replicating the format as defined in your csv.


1 Answers

I finally found the solution:

mypath = customerbulk.objects.get(pk=1).fileup.path o = open(mypath,'rU') mydata = csv.reader(o) 
like image 84
mohd Avatar answered Oct 16 '22 09:10

mohd