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
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.
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.
Including the newline parameter allows the csv module to handle the line endings itself - replicating the format as defined in your csv.
I finally found the solution:
mypath = customerbulk.objects.get(pk=1).fileup.path o = open(mypath,'rU') mydata = csv.reader(o)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With