如何从Python的URL中读取CSV文件? [英] How to read a CSV file from a URL with Python?
本文介绍了如何从Python的URL中读取CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我卷到API调用链接时 http://domain.com/passkey=wedsmdjsjmdd
curl'http://domain.com/passkey=wedsmdjsjmdd'
>
我以csv文件格式获取员工输出数据,例如:
<Steve,421,0,421,2,,, 421,0,421,2
python。
我试过:
import csv
cr = csv.reader(open('http://domain.com/passkey=wedsmdjsjmdd',rb))
在cr中的行:
print row
但它没有工作,我收到一个错误
http://domain.com/passkey=wedsmdjsjmdd没有这样的文件或目录:
谢谢!
解决方案
您需要用 open .org / 2 / library / urllib.html#urllib.urlopen> urllib.urlopen 或 urllib2.urlopen 。
例如
import csv
import urllib2
url ='http://winterolympicsmedals.com/medals.csv'
response = urllib2.urlopen(url)
cr = csv .reader(response)
for row in cr:
print row
这将输出以下
年,城市,运动,纪律,NOC,活动,活动性别,奖章
1924,夏蒙尼,滑冰,花样滑冰,AUT,个人,M,银
1924,夏蒙尼,滑冰,花样滑冰,AUT,个人,W,金
...
when I do curl to a API call link http://domain.com/passkey=wedsmdjsjmdd
curl 'http://domain.com/passkey=wedsmdjsjmdd'
I get the employee output data on a csv file format, like:
"Steve","421","0","421","2","","","","","","","","","421","0","421","2"
how can parse through this using python.
I tried:
import csv
cr = csv.reader(open('http://domain.com/passkey=wedsmdjsjmdd',"rb"))
for row in cr:
print row
but it didn't work and I got an error
http://domain.com/passkey=wedsmdjsjmdd No such file or directory:
Thanks!
解决方案
You need to replace open
with urllib.urlopen or urllib2.urlopen.
e.g.
import csv
import urllib2
url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)
for row in cr:
print row
This would output the following
Year,City,Sport,Discipline,NOC,Event,Event gender,Medal
1924,Chamonix,Skating,Figure skating,AUT,individual,M,Silver
1924,Chamonix,Skating,Figure skating,AUT,individual,W,Gold
...
这篇关于如何从Python的URL中读取CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文