使用“通用换行符”来上传和解析csv文件。在Google App Engine上的python中 [英] Upload and parse csv file with "universal newline" in python on Google App Engine

查看:173
本文介绍了使用“通用换行符”来上传和解析csv文件。在Google App Engine上的python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从GAE的表单上传csv / tsv文件,并尝试使用python csv模块解析该文件。

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

像描述这里,GAE中上传的文件是字符串。

我处理我上传的字符串一个类似文件的对象:

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)

但是我的文件中的新行并不一定是'\\\
'(感谢excel ..),它产生了一个错误:

错误:在非引用字段中看到的新行字符 - 是否需要以通用换行模式打开文件?

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?

有没有人知道如何使用StringIO.StringIO处理字符串像在通用换行打开的文件?

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

推荐答案

如何:

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

或如注释中指出的, csv.reader()支持从列表中输入,因此:

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)

或如果将来 request.get 支持读取模式:

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)

这篇关于使用“通用换行符”来上传和解析csv文件。在Google App Engine上的python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆