简体   繁体   English

使用python检查zip文件中的任何文件夹

[英]Checking for any folder in a zip file using python

I need to write a code which unzips files and should skip a zip file if it detects that there is a folder(any) contained inside it. 我需要编写一个解压缩文件的代码,如果它检测到其中包含一个文件夹(任何),则应该跳过一个zip文件。

I cant find help anywhere i need someone to point me in the right direction i can search for the contents inside the zip file using the code below. 我无法在任何地方找到帮助,我需要有人指出我正确的方向我可以使用下面的代码搜索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())

If you are >= 3.6 you can use ZipInfo.is_dir() 如果你> = 3.6,你可以使用ZipInfo.is_dir()

Something like below: 如下所示:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM