---
title: "从mongodb读取csv解决方案"
author: "iyuan"
date: "2013-05-21T19:41:21Z"
tags: ["GridFS", "MongoDB", "Python", "csv"]
categories: ["编程语言"]
slug: "mongodb-csv"
draft: false
lastmod: "2013-05-21T19:41:45Z"
id: 1872991
url: "https://iyuan.iteye.com/blog/1872991"
---

用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天然好像不支持啊，后来看到这个哥们的[文章](http://madebyknight.com/handling-csv-uploads-in-django/)，建议用splitlines来提前分解掉文件内容，经测试确实好用，也还方便：


```python

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.