2017-08-31 46 views
1

我想从请求的链接下载csv文件并将其保存为MSFT.csv。 然而,我的代码返回错误使用Python保存已下载的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保存呢?

+0

你有熊猫吗? –

+0

@COLDSPEED是的。我有 – lotteryman

回答

1

如果您要将此数据写入CSV文件,您可以先使用requests.get下载该数据。

import requests 

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

如果您使用csv,那么.text内容传递给csv.reader和迭代:

import csv 

with open('out.csv', 'w') as f: 
    writer = csv.writer(f) 
    reader = csv.reader(data.text.splitlines()) 

    for row in reader: 
     writer.writerow(row) 

另外,利用大熊猫,送data.text到缓冲区中,并把它传递给pd.read_csv

import io 
import pandas as pd 

df = pd.read_csv(io.StringIO(data.text)) 
print(df.head()) 

    timestamp open  high  low close adjusted_close volume \ 
0 2017-08-30 73.01 74.2099 72.8293 74.01   74.01 16826094 
1 2017-08-29 72.25 73.1600 72.0500 73.05   73.05 11448677 
2 2017-08-28 73.06 73.0900 72.5500 72.83   72.83 14112777 
3 2017-08-25 72.86 73.3500 72.4800 72.82   72.82 12574503 
4 2017-08-24 72.74 72.8600 72.0700 72.69   72.69 15980144 

    dividend_amount split_coefficient 
0    0.0    1.0 
1    0.0    1.0 
2    0.0    1.0 
3    0.0    1.0 
4    0.0    1.0 

df.to_csv('out.csv') 
+0

使用'import csv'的代码对我来说非常完美。与使用网页浏览器下载的文件相比,熊猫的版本并不是那么完美。几个字节的差异可能是。 – eddys

+0

@eddys我看到...尝试直接将url字符串传递给read_csv。这可能会更好。 –

-1

在这里你去

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

您可以通过请求实现它作为

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

你可以调用函数与您的网址和文件名,你想要的。在你的情况下,它会是:

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

希望这有助于。