使用 Python 保存下载的 CSV 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45978295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:24:05  来源:igfitidea点击:

Saving a downloaded CSV file using Python

pythonpandascsvpython-requests

提问by lotteryman

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

我想从带有请求的链接下载一个 csv 文件并将其保存为 .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?

文件“< stdin >”,第 1 行,在 _csv.Error: 未加引号的字段中看到换行符 - 您是否需要以通用换行符模式打开文件?

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?

我怎样才能保存它MSFT.csv

回答by cs95

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.

如果您尝试将此数据写入 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(','))


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

或者,如果您安装了 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')

回答by Sagun Shrestha

You can achieve it via requests as

您可以通过请求实现它

import os
import requests

def download_file(url, filename):
    ''' Downloads file from the url and save it as filename '''
    # check if file already exists
    if not os.path.isfile(filename):
        print('Downloading File')
        response = requests.get(url)
        # Check if the response is ok (200)
        if response.status_code == 200:
            # Open file and write the content
            with open(filename, 'wb') as file:
                # A chunk of 128 bytes
                for chunk in response:
                    file.write(chunk)
    else:
        print('File exists')

You can call the function with your url and filename that you want. In your case it would be:

您可以使用所需的 url 和文件名调用该函数。在您的情况下,它将是:

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

Hope this helps.

希望这可以帮助。

回答by Ahmed AbdelKhalek

There is a simpler way for you.

有一个更简单的方法。

import urllib.request

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

urllib.request.urlretrieve(csv_url, 'MSFT.csv')

回答by markroxor

Here you go

干得好

import requests, csv

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

with open('MSFT.csv', 'w') as temp_file:
    temp_file.writelines(download.content)