从HTTP响应到CSV

时间:2018-11-13 14:05:37

标签: python python-3.x python-2.7 python-requests

我需要将数据从URL导出到csv,此代码有效,但是位于此URL上的数据写成一个没有定界符的字符串,如何解决呢?

import urllib
import pandas as pd

URL="https://www.star.nesdis.noaa.gov/smcd/emb/vci/NPP_VH/4km/ts_L1_v1/ByWeek/VHP_L1_Mean_198135.txt"
vhi_url = urllib.request.urlopen(URL)
out = open('vhi_id_16.csv','wb')
out.write(vhi_url.read())
out.close()

1 个答案:

答案 0 :(得分:0)

使用您的代码的以下细微变化:

from urllib import request

with open('vhi_id_16.csv', 'w') as out:
    with request.urlopen('PUT_URL_HERE') as response:
        encoding = response.headers.get_content_charset('utf-8')
        out.write(response.read().decode(encoding))
        out.close()