Open the file in universal-newline mode using the CSV Django module
78,096
I finally found the solution:
mypath = customerbulk.objects.get(pk=1).fileup.path
o = open(mypath,'rU')
mydata = csv.reader(o)
Author by
mohd
Updated on July 12, 2022Comments
-
mohd almost 2 years
I am trying to access a
model.filefield
in Django to parse a CSV file in Python using thecsv
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
-
GajananB almost 11 yearsI believe you can simplify this. It seems odd to seek to the start after just opening the file. The following helped me overcome the same issue from an Excel spreadsheet export to CSV using the defaults: data = csv.reader(open(FILENAME, 'rU'), quotechar='"', delimiter = ',')
-
rd108 almost 11 yearsYes, there's no need to seek to beginning of file just after opening. The >>>o = open(mypath, 'rU') bit, with the 'rU' flag is the important magic that worked in my case.
-
Xiao over 10 yearsPEP278 explained what
rU
stands for:In a Python with universal newline support open() the mode parameter can also be "U", meaning "open for input as a text file with universal newline interpretation". Mode "rU" is also allowed, for symmetry with "rb".
-
Naymesh Mistry over 6 years@Xiao +1 for linking to the original PEP which explains the rationale.
-
Tim Diels about 5 yearsIn Python >= 3, use
newline
instead, the default isnewline=None
which is likenewline=''
except it also translates the newlines to\n
. I'm unsure which of these is equivalent tomode='U'