如何使用 Python 从 URL 读取 CSV 文件? [英] How to read a CSV file from a URL with Python?

查看:49
本文介绍了如何使用 Python 从 URL 读取 CSV 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我 curl 到 API 调用链接时 http://example.com/passkey=wedsmdjsjmdd

when I do curl to a API call link http://example.com/passkey=wedsmdjsjmdd

curl 'http://example.com/passkey=wedsmdjsjmdd'

我以 csv 文件格式获取员工输出数据,例如:

I get the employee output data on a csv file format, like:

"Steve","421","0","421","2","","","","","","","","","421","0","421","2"

如何使用 python 解析这个.

how can parse through this using python.

我试过了:

import csv 
cr = csv.reader(open('http://example.com/passkey=wedsmdjsjmdd',"rb"))
for row in cr:
    print row

但它没有用,我遇到了一个错误

but it didn't work and I got an error

http://example.com/passkey=wedsmdjsjmdd 没有那个文件或目录:

谢谢!

推荐答案

您需要将 open 替换为 urllib.urlopenurllib2.urlopen.

You need to replace open with urllib.urlopen or 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

这将输出以下内容

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-2.x",但对于 Python 3 实现(只需要少量更改)见下文.

The original question is tagged "python-2.x", but for a Python 3 implementation (which requires only minor changes) see below.

这篇关于如何使用 Python 从 URL 读取 CSV 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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