python - 使用 Python 保存下载的 CSV 文件

标签 python pandas csv python-requests

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

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 文件。

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

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

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 - 使用 Python 保存下载的 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45978295/

相关文章:

python - 使用 scipy.io.loadmat 从 .mat Matlab 文件将字典键转换为在 Python 中具有相同值的变量名

python - Shebang 用于已编译的 Python 代码

python - 有效地转换 Pandas 中的数据

python - Pandas:如何使用 json 数组分解数据框

r - Sparklyr 忽略行分隔符

python - 将 "missing array values"写入文件

python - Python中的多个 'or'条件

python - 如何在一个矩阵中连接多个向量(每个向量是新矩阵的一列)

python - 仅删除组内的重复项

ruby-on-rails - 在rails中,如何将记录作为csv文件返回