python - shutil.copyfileobj 错误地复制了数据

标签 python

为了处理一些图片(下载、检测格式和存储),我使用以下代码:

image = urllib.request.urlopen(img_url)
buf = io.BytesIO()
shutil.copyfileobj(image, buf)
ext = imghdr.what(buf)

ext 为空(意味着无法检测到格式)。我尝试以不同的方式重做:

image = urllib.request.urlopen(link)
test = image.read()
binbuf = io.BytesIO(test)
imghdr.what(binbuf)

这确实奏效了。我的结论是 copyfileobj 以某种方式搞砸了。为什么会这样?

最佳答案

shutil.copyfileobj(image, buf)写入buf后,buf的流指针指向下一个位置在你刚刚写入的数据结束之后。当您尝试执行 ext = imghdr.what(buf) 时,它不会读取任何内容(因为从该位置没有更多内容可读取)并返回 None。在尝试读取您刚刚编写的内容之前,您需要将 .seek() 返回到 0

这个有效:

image = urllib.request.urlopen(img_url)
buf = io.BytesIO()
shutil.copyfileobj(image, buf)
buf.seek(0)
ext = imghdr.what(buf)

关于python - shutil.copyfileobj 错误地复制了数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32147491/

相关文章:

python - 在 Django 中允许每个用户生成 1 个 View

python - 在 python 中初始化整数数组的最快方法是什么?

python - 使用 Beaker 缓存和 SQLAlchemy

python - 如何转发/填充 Pandas DataFrame 列/系列中的特定值?

python - 为什么TensorFlow的Fashion MNIST问题中keras神经网络第二层有128个节点

python - 如何在对象列表中查找字符串的最大长度(Python)

python子进程的使用

Python 循环不工作 (xlwt)

Python:线程回调不适用于守护进程模式?

python - Django 应用程序中的线程