Skip to main content
 首页 » 编程设计

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

2024年10月17日5softidea

我有一个 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