如何读取本身位于 zip 文件中的文件夹中的文件

How to read a file inside a folder which itself is inside a zip file

我有一个 zip 文件,它包含一个与 zip 文件同名的文件夹(即,如果 zip 文件夹的名称是 1.zip,则 zip 文件中的文件夹名称将是 1.)
现在这个文件夹包含一个文本文件 atextfile.txt,我想打印这个文件的内容。
如果 atextfile.txt 就在 zip 文件中,我就写了代码。

    for zip_name in glob.glob('[0-9].zip'):
    # the zip file name one numeric digit only.
        z=zipfile.ZipFile(zip_name)
        with z.open('atextfile.txt') as f:
            for line in f:
                for word in line:
                    print word

我不知道现在该怎么办。请帮忙。

您可以将路径名添加到您使用 ZipFile.open() 提取的文件名中。以下是使用您在问题中描述的命名方案自动执行此操作的方法:

for zip_name in glob.glob('[0-9].zip'):
# the zip file name one numeric digit only.
    z=zipfile.ZipFile(zip_name)
    subdir = zip_name[:-4]    # the glob pattern ensures that the file name ends with ".zip", so strip off the extension
    with z.open('{}/atextfile.txt'.format(subdir)) as f:
        for line in f:
            for word in line:
                print word