pythonrequest请求下载csv文件保存_使用Python保存下载的CSV文件

I want to download a csv file from a link with request and save it as MSFT.csv.

However, my code return error

File "< stdin >", line 1, in

_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

import requests

import csv

data=requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&apikey=demo&datatype=csv'

cr = csv.reader(data)

for row in cr:

print row

How can I save it with MSFT.csv?

解决方案

If you're trying to write this data to a CSV file, you can first download it using requests.get, then save each line to a CSV file.

import csv

import requests

url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&apikey=demo&datatype=csv'

response = requests.get(url)

with open('out.csv', 'w') as f:

writer = csv.writer(f)

for line in response.iter_lines():

writer.writerow(line.decode('utf-8').split(','))

Alternatively, if you have pandas installed (pip install --user pandas), you can load data by passing a URL directly.

import pandas as pd

df = pd.read_csv(url)

df.head()

timestamp open high low close adjusted_close volume dividend_amount split_coefficient

0 2019-06-19 135.00 135.93 133.81 135.69 135.69 17946556 0.0 1.0

1 2019-06-18 134.19 135.24 133.57 135.16 135.16 25908534 0.0 1.0

2 2019-06-17 132.63 133.73 132.53 132.85 132.85 14517785 0.0 1.0

3 2019-06-14 132.26 133.79 131.64 132.45 132.45 17821703 0.0 1.0

4 2019-06-13 131.98 132.67 131.56 132.32 132.32 17200848 0.0 1.0

df.to_csv('out.csv')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值