python - 使用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())
解决方案
如果您 >= 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)
推荐阅读
- kotlin - 如何将同一字符串的多个副本添加到现有的 ArrayList?
- android - 如何在协程中进行同步 API 调用?
- android - 如何在 Android 上使用 NDK 和 AssetManager 读写二进制文件?
- woocommerce - Woocommerce rest api not working 401 unauthorised
- ionic5 - 如何在 ionicreact5 中删除 ion-row 和 ion-col 的空间(边距/填充)?
- c++ - -Ofast 在使用 long double 时产生不正确的代码
- java - 适配器不显示 Firebase 实时数据库中的产品图片和价格
- django - django-rest-framework – 如何序列化嵌套对象?
- python - 如何在 Python 中查看多个 Excel 行
- spinnaker - 为什么 /var/log/spinnaker 上没有日志