You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Python处理ZIP图片时出现'ZipFile'对象无'seek'属性的错误

问题原因
  • 传参错误:你调用display_newsfile()时传入的是之前with语句中已经关闭的ZipFile对象,而print_file()可以正常运行是因为你传入的是压缩包路径字符串small_img。zipfile.ZipFile()构造函数仅支持接收文件路径字符串、或具备seek方法的原生文件对象,传入已关闭的ZipFile实例会触发属性不存在的报错。
  • 函数逻辑冗余:display_newsfile()内部已经通过with ZipFile(small_img, 'r')打开了压缩包,无需重复实例化ZipFile对象。
  • 文件读取逻辑错误:infolist()返回的是压缩包条目的元数据,不是可直接读取的类文件对象,需要通过ZipFile.open(条目)才能拿到可供Image.open()读取的文件流。
修复后的代码
import zipfile
from zipfile import ZipFile
from PIL import Image

small_img = "readonly/small_img.zip"

# 原解压逻辑保持不变
with ZipFile(small_img, 'r') as zip:
    zip.printdir()
    print('Extracting all the files now...')
    zip.extractall()
    print('Done!')

# 原打印文件名函数保持不变
def print_file(archive_name):
    zf = zipfile.ZipFile(archive_name)
    for info in zf.infolist():
        print('File Name:' + info.filename)    

print_file(small_img)

# 修正后的展示文件函数
def display_newsfile(archive_name):
    with ZipFile(archive_name, 'r') as zf:
        for info in zf.infolist():
            # 从压缩包中读取文件流传给Image.open
            with zf.open(info) as img_stream:
                image = Image.open(img_stream)
                display(image)

# 传入压缩包路径字符串,而非已关闭的ZipFile对象
display_newsfile(small_img)

内容的提问来源于stack exchange,提问作者LetsGetTr0pical

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:27:01