我一直在尝试使用requests库从服务器主机URL下载压缩的csv。
当我从同一服务器下载一个不需要压缩的小文件时,它在CSV中读取没有问题,但对于这个文件,我返回了编码错误。
我尝试了多种编码方式,以pandas csv格式读入,以zip文件格式读入,然后打开(此时我得到的错误消息是,文件不是zip文件)。
我还尝试了使用这里建议的zipfile库:Reading csv zipped files in python
并且还尝试在read_csv
中设置编码和压缩。
适用于未压缩的服务器文件的代码如下:
response = requests.get(url, auth=HTTPBasicAuth(un, pw), stream=True, verify = False)
dfs = pd.read_csv(response.raw)
但用于此文件时返回'utf-8' codec can't decode byte 0xfd in position 0: invalid start byte
。
我也尝试过:
request = get(url, auth=HTTPBasicAuth(un, pw), stream=True, verify=False)
zip_file = ZipFile(BytesIO(request.content))
files = zip_file.namelist()
with gzip.open(files[0], 'rb') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
print(row)
这将返回查找属性错误。
发布于 2021-02-09 04:42:40
这里有一种方法:
import pandas as pd
import requests
from requests.auth import HTTPBasicAuth
from zipfile import ZipFile
import io
# Example dataset
url = 'https://www.stats.govt.nz/assets/Uploads/Retail-trade-survey/Retail-trade-survey-September-2020-quarter/Download-data/retail-trade-survey-september-2020-quarter-csv.zip'
response = requests.get(url, auth=HTTPBasicAuth(un, pw), stream=True, verify=False)
with ZipFile(io.BytesIO(response.content)) as myzip:
with myzip.open(myzip.namelist()[0]) as myfile:
df = pd.read_csv(myfile)
print(df)
如果要读取多csv压缩文件中的特定csv,请将myzip.namelist()[0]
替换为要读取的文件。如果您不知道其名称,可以使用print(ZipFile(io.BytesIO(response.content)))
检查zip
文件内容
https://stackoverflow.com/questions/66108822
复制相似问题