无法使用 ZipFile 打开子目录中的文件

Cannot open file in subdirectory with ZipFile

出于某种原因我无法打开或访问此子目录中的文件。我需要能够打开和读取压缩文件夹子目录中的文件。这是我的代码。

import zipfile
import os

for root, dirs, files in os.walk('Z:\STAR'):
    for name in files:
        if '.zip' in name:
            try:
                zipt=zipfile.ZipFile(os.path.join(root,name),'r')
                dirlist=zipfile.ZipFile.namelist(zipt)
                for item in dirlist:
                    if 'Usb' in item:
                        input(item)
                        with zipt.open(item,'r') as f:
                            a=f.readlines()
                            input(a[0])
                    else:pass
            except Exception as e:
                print('passed trc file {}{} because of {}'.format(root,name,e))
        else:pass

这段代码目前给我的错误是:

File "StarMe_tracer2.py", line 133, in tracer
    if 'er99' in line:
TypeError: a bytes-like object is required, not 'str'

从使用 ZipFile.open 打开的文件对象中读取的内容是字节而不是字符串,因此测试字符串 'er99' 是否在字节行中会失败并返回 TypeError.

相反,您可以在测试之前解码该行:

if 'er99' in line.decode():

或使用 io.TextIOWrapper:

将字节流转换为文本流
import io

...

with io.TextIOWrapper(zipt.open(item,'r'), encoding='utf-8') as f: