从CSV文件

时间:2015-06-08 20:58:06

标签: python csv

我正在访问API,然后将数据输出到CSV文件,如下所示:

from urllib2 import Request, urlopen, URLError
import csv
request = Request('https://www.quandl.com/api/v1/datasets/YC/CHE10Y.csv?   auth_token=AUTH_TOKEN') # Data available in CSV Format

try:
    response = urlopen(request)
    datafromfile = response.read()
    with open('QuandlData.csv', 'w') as out:
        writer = csv.writer(out)
    for data in datafromfile:
        writer.writerow(data);

except URLError, e:
    print 'No data. Got an error code:', e

这是输出数据。但是,数据如下:

D

a

t

e

,

R

a

t

e

"
"

2

0

1

5

-

0

6

-

0

5

,

0

我理解这与我将数据输出到CSV文件的方式有关。但是,我不知道如何纠正这个问题。

4 个答案:

答案 0 :(得分:1)

您正在迭代从response.read()返回的字符,因此一次只能写一个字符。如果你想写行:

writer.writerows(response.read().splitlines())

或者只需用file.write写一下response.read()

你基本上是这样做的:

In [12]: for c in s:
             print(c)
   ....:     
f
o
o
b
a
r

答案 1 :(得分:0)

更容易,

import urllib
import csv

url = 'https://www.quandl.com/api/v1/datasets/YC/CHE10Y.csv?auth_token=mv1c1_V3kqVeL4yyjPZA'
urllib.urlretrieve(url, '/path-to-file/30718958.csv')

您输出的原因是形成的结果集是单一的。因此,迭代以单个数字执行。请避免在网址中逃脱。

答案 2 :(得分:0)

不要一起阅读文件,你不知道它有多大。如果要编写CSV行,则需要将list之类的可迭代类型传递给writerow。基本上,您需要将数据拆分为其列。

以下是我的建议,您需要更改try的块:

response = urlopen(request)
with open('QuandlData.csv', 'w') as out:
    writer = csv.writer(out)
    for data in response:
        writer.writerow(data.strip().split(','))

答案 3 :(得分:0)

由于回复是 csv ,另一个选项是使用csv.reader阅读回复:

from urllib2 import Request, urlopen, URLError
import csv
request = Request('https://www.quandl.com/api/v1/datasets/YC/CHE10Y.csv?auth_token=mv1c1_V3kqVeL4yyjPZA') #% Data available in CSV Format
try:
    response = urlopen(request)
    # read with csv.reader
    datafromfile = csv.reader(response)
    with open('QuandlData.csv', 'w') as out:
        writer = csv.writer(out)
        for data in datafromfile:
            writer.writerows([data])

except URLError, e:
    print 'No data. Got an error code:', e

我得到一个看起来像的文件:

Date,Rate
2015-06-08,0.13
2015-06-05,0.12
2015-06-04,0.13
2015-06-03,0.01
2015-06-02,-0.05
...