有人可以说明我的代码有什么问题以及到底是什么导致了此错误吗?我是Python初学者,我想将一些JPG加载到该网络中。通常,我一直在尝试通过试错法来解决问题,并在此网站上进行故障排除。这些东西伤了我的大脑,所以请帮个新手。
先谢谢您!
达伦
错误:
{
"requestedUrl": "https://www.googleapis.com/books/v1/volumes?q=java&maxResults=40",
"items": [
{
"kind": "books#volume",
"id": "7tkN1CYzn2cC",
"etag": "pfjjxSpetIM",
"selfLink": "https://www.googleapis.com/books/v1/volumes/7tkN1CYzn2cC",
"volumeInfo": {
"title": "A Hypervista of the Java Landscape",
"publisher": "InfoStrategist.com",
"industryIdentifiers": [
{
"type": "ISBN_13",
"identifier": "9781592432172"
},
{
"type": "ISBN_10",
"identifier": "1592432174"
}
],
"readingModes": {
"text": true,
"image": true
},
"printType": "BOOK",
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "1.0.1.0.preview.3",
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=7tkN1CYzn2cC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=7tkN1CYzn2cC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.pl/books?id=7tkN1CYzn2cC&pg=PP1&dq=java&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.pl/books?id=7tkN1CYzn2cC&dq=java&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/A_Hypervista_of_the_Java_Landscape.html?hl=&id=7tkN1CYzn2cC"
},
"saleInfo": {
"country": "PL",
"saleability": "NOT_FOR_SALE",
"isEbook": false
}, //Shortened for brevity
代码:
Traceback (most recent call last):
File "gan3.py", line 30, in <module>
content = open(os.path.join(path, filename)).read()
File "/Users/darren/miniconda3/lib/python3.7/codecs.py", line 322, in
decode (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0:
invalid start byte
干杯们!
答案 0 :(得分:1)
默认情况下,open
以文本模式打开文件。当您从中读取数据时,Python会自动尝试将您的数据转换为字符串,因为这不是UTF-8编码的文本,所以会失败。
如果它是图像,则必须以二进制模式打开它:
content = open(os.path.join(path, filename), mode='rb').read()
答案 1 :(得分:1)
您可以使用PIL库打开图像文件:
from PIL import Image
#<----code---->
content = Image.open(os.path.join(path, filename))