简体   繁体   English

Python - Pandas:如何从 url 保存 csv 文件

[英]Python - Pandas : how to save csv file from url

so I'm trying to get a csv file with requests and save it to my project:所以我试图获取一个带有请求的 csv 文件并将其保存到我的项目中:

import requests
import pandas as pd
import csv

def get_and_save_countries():
    url = 'https://www.trackcorona.live/api/countries'
    r = requests.get(url)
    data = r.json()
    data = data["data"]
  
    with open("corona/dash_apps/finished_apps/apicountries.csv","w",newline="") as f:  
        title = "location,country_code,latitude,longitude,confirmed,dead,recovered,updated".split(",") 
        cw = csv.DictWriter(f,title,delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
        cw.writeheader()
        cw.writerows(data)

I've managed that but when I try this:我已经做到了,但是当我尝试这样做时:

get_data.get_and_save_countries()
df = pd.read_csv("corona\\dash_apps\\finished_apps\\apicountries.csv")

I get this error:我收到此错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 1: invalid continuation byte

And I have no idea why.我不知道为什么。 Any help is welcome.欢迎任何帮助。 Thanks.谢谢。

Try:尝试:

 with open("corona/dash_apps/finished_apps/apicountries.csv","w",newline="", encoding ='utf-8') as f:

to explicitly specify the encoding with encoding='utf-8'使用encoding='utf-8'显式指定编码

When you write to a file, the default encoding is locale.getpreferredencoding(False) .写入文件时,默认编码为locale.getpreferredencoding(False) On Windows that is usually not UTF-8 and even on Linux the terminal could be configured other than UTF-8.在通常不是 UTF-8 的 Windows 上,甚至在 Linux 上,终端也可以配置为非 UTF-8。 Pandas is defaulting to utf-8 , so specify encoding='utf8' as another parameter to open . Pandas 默认为utf-8 ,因此将encoding='utf8'指定为open另一个参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM