Python CSV读取器不是以我期望的方式读取CSV数据 [英] Python CSV reader isn't reading CSV data the way I expect

查看:1789
本文介绍了Python CSV读取器不是以我期望的方式读取CSV数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取一些CSV数据到数组中。我可以解释一下我在Python中比英语做得更好:

I'm trying to read some CSV data into an array. I can probably explain what I'm trying to do better in Python than in English:

>>> line = ImportFile.objects.all().reverse()[0].file.split("\n")[0]
>>> line
'"007147","John Smith","100 Farley Ln","","Berlin NH 03570","Berlin","NH",2450000,"John",24643203,3454,"E","",2345071,1201,"N",15465,"I",.00,20102456,945610,20247320,1245712,"0T",.00100000,"",.00,.00,780,"D","000",.00,0\r'
>>> s = cStringIO.StringIO()
>>> s
<cStringIO.StringO object at 0x9ab1960>
>>> s.write(line)
>>> r = csv.reader(s)
>>> r
<_csv.reader object at 0x9aa217c>
>>> [line for line in r]
[]

如您所见,CSV数据在内存中启动,而不是在文件中启动。我希望我的读者有一些数据,但它不。

As you can see, the CSV data starts in memory, not in a file. I would expect my reader to have some of that data but it doesn't. What am I doing wrong?

推荐答案

您在使用 StringIO 错误的方法。尝试

You are using StringIO in the wrong way. Try

s = cStringIO.StringIO(line)
r = csv.reader(s)
next(r)
# "['007147', 'John Smith', '100 Farley Ln', '', 'Berlin NH 03570', 'Berlin', 'NH', '2450000', 'John', '24643203', '3454', 'E', '', '2345071', '1201', 'N', '15465', 'I', '.00', '20102456', '945610', '20247320', '1245712', '0T', '.00100000', '', '.00', '.00', '780', 'D', '000', '.00', '0']"

,结果应该是您期望的结果。

and the result should be what you expect.

编辑:更详细地说明:在写入 StringIO 实例后,文件指针将指向内容的末尾。这是您期望通过随后的 write()调用写入新内容的位置。但这也意味着 read()调用不会返回任何内容。您需要调用 s.reset() s.seek(0)将位置重置为开始,或者用所需的内容初始化 StringIO

Edit: To explain in more detail: After writing to the StringIO instance, the file pointer will point past the end of the contents. This is where you would expect new contents to be written by subsequent write() calls. But this also means that read() calls will not return anything. You would need to call s.reset() or s.seek(0) to reset the position to the beginning, or initialise the StringIO with the desired contents.

这篇关于Python CSV读取器不是以我期望的方式读取CSV数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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