2017-08-31 47 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) 

希望這有助於。