我需要编写一个解压缩文件的代码,如果它检测到其中包含文件夹(任何文件),则应跳过一个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())
答案 0 :(得分:0)
如果您> = 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)