python读取字符串的list dict_Python csv.DictReader:解析字符串?

1586010002-jmsa.png

I am downloading a CSV file directly from a URL using requests.

How can I parse the resulting string with csv.DictReader?

Right now I have this:

r = requests.get(url)

reader_list = csv.DictReader(r.text)

print reader_list.fieldnames

for row in reader_list:

print row

But I just get ['r'] as the result of fieldnames, and then all kinds of weird things from print row.

解决方案

From documentation of csv , the first argument to csv.reader or csv.DictReader is csvfile -

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

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.

Hence, you need to either provide a in-memory stream of the string (Using StringIO) or a list of lines (using splitlines)

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'}

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'}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值