首页 > 解决方案 > 使用python检查zip文件中的任何文件夹

问题描述

我需要编写一个解压缩文件的代码,如果它检测到其中包含一个文件夹(任何),则应该跳过一个 zip 文件。

我无法在任何需要有人指出正确方向的地方找到帮助,我可以使用下面的代码搜索 zip 文件中的内容。

dir_name = 'C:\\Users\Desktop\Python'
extension = ".zip"

os.chdir(dir_name)  # change directory from working dir to dir with files

for item in os.listdir(dir_name):  # loop through items in dir

    if item.endswith(extension):  # check for ".zip" extension
        file_name = os.path.abspath(item)  # get full path of files
        zip_ref = zipfile.ZipFile(file_name)  # create zipfile object
        print (zip_ref.namelist())

标签: pythonpython-3.xzip

解决方案


如果您 >= 3.6,您可以使用ZipInfo.is_dir()

如下所示:

dir_name = "/desired/path"
extension = ".zip"

os.chdir(dir_name)  # change directory from working dir to dir with files
for item in os.listdir(dir_name):  # loop through items in dir
    print('item is ', item)
    if not item.endswith(extension):
        continue
    with zipfile.ZipFile(os.path.abspath(item)) as file:
        print('file to check is ', file)
        has_folder = any([a for a in file.infolist() if zipfile.ZipInfo.is_dir(a)])
        print(' has folder ', has_folder, ' file is ', item)

推荐阅读