Python csv.DictReader:解析字符串? [英] Python csv.DictReader: parse string?
问题描述
我正在直接使用requests
从URL下载CSV文件.
I am downloading a CSV file directly from a URL using requests
.
如何用csv.DictReader
解析结果字符串?
How can I parse the resulting string with csv.DictReader
?
现在我有这个了
r = requests.get(url)
reader_list = csv.DictReader(r.text)
print reader_list.fieldnames
for row in reader_list:
print row
但是我只是得到['r']
作为fieldnames
的结果,然后得到来自print row
的各种奇怪的东西.
But I just get ['r']
as the result of fieldnames
, and then all kinds of weird things from print row
.
推荐答案
来自 csv.reader
或csv.DictReader
的第一个参数是csvfile
-
From documentation of csv
, the first argument to csv.reader
or csv.DictReader
is csvfile
-
csvfile可以是任何支持迭代器协议的对象,并且每次调用next()方法时都会返回一个字符串-文件对象和列表对象都适用
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
在您将字符串作为csv.DictReader()
的直接输入的情况下,对它的next()
调用仅提供一个字符,因此成为标题,然后持续调用next()以获取每一行.
In your case when you give the string as the direct input for the csv.DictReader()
, the next()
call on it only provides a single character, and hence that becomes the header, and then next() is continuously called to get each row.
因此,您需要提供字符串的内存流(使用StringIO)或行列表(使用splitlines
)
Hence, you need to either provide a in-memory stream of the string (Using StringIO) or a list of lines (using splitlines
)
您可以使用 io.StringIO()
,然后在csv.DictReader
中使用它.示例/演示-
You can use io.StringIO()
and then use it in csv.DictReader
. Example/Demo -
>>> import csv
>>> s = """a,b,c
... 1,2,3
... 4,5,6
... 7,8,9"""
>>> import io
>>> reader_list = csv.DictReader(io.StringIO(s))
>>> print reader_list.fieldnames
['a', 'b', 'c']
>>> for row in reader_list:
... print row
...
{'a': '1', 'c': '3', 'b': '2'}
{'a': '4', 'c': '6', 'b': '5'}
{'a': '7', 'c': '9', 'b': '8'}
或者如注释中所示,您可以先分割行,然后再输入csv.DictReader
.示例/演示-
Or as indicated in the comments , you can split the lines before giving as input to csv.DictReader
. Example/Demo -
>>> reader_list = csv.DictReader(s.splitlines())
>>> print reader_list.fieldnames
['a', 'b', 'c']
>>> for row in reader_list:
... print row
...
{'a': '1', 'c': '3', 'b': '2'}
{'a': '4', 'c': '6', 'b': '5'}
{'a': '7', 'c': '9', 'b': '8'}
这篇关于Python csv.DictReader:解析字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!