Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload and parse csv file with "universal newline" in python on Google App Engine

I'm uploading a csv/tsv file from a form in GAE, and I try to parse the file with python csv module.

Like describe here, uploaded files in GAE are strings.
So I treat my uploaded string a file-like object :

file = self.request.get('catalog')
catalog = csv.reader(StringIO.StringIO(file),dialect=csv.excel_tab)

But new lines in my files are not necessarily '\n' (thanks to excel..), and it generated an error :
Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

Does anyone know how to use StringIO.StringIO to treat strings like files open in universal-newline?

like image 234
greg Avatar asked Mar 17 '11 15:03

greg


People also ask

How do I handle a new line character in a CSV file?

Specifying and Saving Newline Characters Open a CSV file in the text editor. Click Save As from the menu. Specify "CR+LF" or "LF" as a newline character and save the file.

What does newline mean in Python CSV?

The csv module does its own handling of newlines within Reader objects, so it wants the file object to pass along the newline characters unmodified. That's what newline='' tells the open function you want. Follow this answer to receive notifications. answered Dec 20, 2021 at 22:42.

Can CSV contain new line?

If you upload a CSV file that contains new line characters in the fields other than Text Area Field, it will be saved to the system but only Text Area Field preserves the new line if you edit the Asset. Other fields like "Text Field" will trim the new line character if you edit and save Asset at Asset Edit page.

How do I add a line to a CSV file in Python?

Open your CSV file in append mode Create a file object for this file. Pass the file object and a list of column names to DictWriter() You will get an object of DictWriter. Pass the dictionary as an argument to the writerow() function of DictWriter (it will add a new row to the CSV file).


1 Answers

How about:

file = self.request.get('catalog')
file  = '\n'.join(file.splitlines())
catalog = csv.reader(StringIO.StringIO(file),dialect=csv.excel_tab)

or as pointed out in the comments, csv.reader() supports input from a list, so:

file = self.request.get('catalog')
catalog = csv.reader(file.splitlines(),dialect=csv.excel_tab)

or if in the future request.get supports read modes:

file = self.request.get('catalog', 'rU')
catalog = csv.reader(StringIO.StringIO(file),dialect=csv.excel_tab)
like image 180
theheadofabroom Avatar answered Oct 06 '22 01:10

theheadofabroom