使用Python保存下载的CSV文件 [英] Saving a downloaded CSV file using Python

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

问题描述

我想从带有请求的链接中下载一个csv文件,并将其另存为MSFT.csv. 但是,我的代码返回错误

I want to download a csv file from a link with request and save it as MSFT.csv. However, my code return error

文件< stdin>",第1行,在 _csv.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

如何用MSFT.csv保存它?

推荐答案

如果要将此数据写入CSV文件,可以先使用requests.get下载,然后将每一行保存到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(','))


或者,如果您安装了熊猫(pip install --user pandas),则可以通过直接传递URL来加载数据.


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')

这篇关于使用Python保存下载的CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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