ITeye博客

从mongodb读取csv解决方案

iyuan · 2013-05-21 19:41 · python · 编程语言 · MongoDB · Python · csv · GridFS · Markdown

用Python中的csv模块读.csv文件还是蛮赞的,特别是DictReader这种pythoner喜闻乐见的自动转字典的方式。

不过在直接从mongodb中读取csv就杯具了:new-line character seen in unquoted field – do you need to open the file in universal-newline mode?

网上普遍的做法是,传递file的时候通过open(fpath,'rU')来控制文件的分段,pymongo天然好像不支持啊,后来看到这个哥们的文章,建议用splitlines来提前分解掉文件内容,经测试确实好用,也还方便:


f = fs.get(fid)
reader = DictReader(f.read().splitlines())

这尼玛竟然不一定要传file object的啊... 文档中的这句没有看到,着实让人吐血啊:

csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。