我可以将 Python 的 CSV 阅读器与 Google Fusion Tables 一起使用吗?
我正在尝试使用 csv 库将 Google Fusion Tables API 中的数据读取到 Python 中。查询 API 似乎返回 CSV 数据,但是当我尝试将其与 csv.reader 一起使用时,它似乎会破坏数据并将其拆分为每个字符,而不仅仅是逗号和换行符。我是不是少了一步?这是我使用公共表进行说明的示例:
#!/usr/bin/python
import csv
import urllib2, urllib
request_url = 'https://www.google.com/fusiontables/api/query'
query = 'SELECT * FROM 1140242 LIMIT 10'
url = "%s?%s" % (request_url, urllib.urlencode({'sql': query}))
serv_req = urllib2.Request(url=url)
serv_resp = urllib2.urlopen(serv_req)
reader = csv.reader(serv_resp.read())
for row in reader:
print row #prints out each character of each cell and the column headings
最终我将使用 csv.DictReader 类,但基本 reader 也显示了问题
I'm trying to read data from Google Fusion Tables API into Python using the csv library. It seems like querying the API returns CSV data, but when I try and use it with csv.reader, it seems to mangle the data and split it up on every character rather than just on the commas and newlines. Am I missing a step? Here's a sample I made to illustrate, using a public table:
#!/usr/bin/python
import csv
import urllib2, urllib
request_url = 'https://www.google.com/fusiontables/api/query'
query = 'SELECT * FROM 1140242 LIMIT 10'
url = "%s?%s" % (request_url, urllib.urlencode({'sql': query}))
serv_req = urllib2.Request(url=url)
serv_resp = urllib2.urlopen(serv_req)
reader = csv.reader(serv_resp.read())
for row in reader:
print row #prints out each character of each cell and the column headings
Ultimately I'd be using the csv.DictReader class, but the base reader shows the issue as well
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
csv.reader()
接受一个类似文件的对象。更改
为
或者,您可以这样做:
csv.reader()
takes in a file-like object.Change
to
Alternatively, you could do:
导致问题的不是 CSV 模块。查看 serv_resp.read() 的输出。尝试使用
serv_resp.readlines()
代替。It's not the CSV module that's causing the problem. Take a look at the output from
serv_resp.read()
. Try usingserv_resp.readlines()
instead.