如何确定 python ZipFile 中的项目是目录还是文件?
How do I determine whether an item in python ZipFile is dir or file?
这是我目前的系统,它只是查看路径中是否有句点...但这并不适用于所有情况
with ZipFile(zipdata, 'r') as zipf: #Open the .zip BytesIO in Memory
mod_items = zipf.namelist() #Get the name of literally everything in the zip
for folder in mod_folders:
mod_items.insert(0, folder)
#Put the folder at the start of the list
#This makes sure that the folder gets created
#Search through every file in the .zip for each folder indicated in the save
for item in mod_items:
if folder in item: #If the item's path indicates that it is a member of the folder
itempath = item #Make a copy of the
if not itempath.startswith(folder):
itempath = path_clear(itempath, folder)
if not 'GameData/' in itempath:
itempath = 'GameData/' + itempath
path = mod_destination_folder + '/' + itempath
path = path_clear(path)
dot_count = path.count('.')
if dot_count: #Is a normal file, theoretically
itemdata = zipf.read(item)
try:
with open(path, 'wb') as file:
file.write(itemdata)
except FileNotFoundError as f:
folder_path = path[:path.rfind('/')]
makedirs(folder_path)
with open(path, 'wb') as file:
file.write(itemdata)
else: #Is a folder
try: makedirs(path)
except: pass
我只需要某种方法来确定是否:
A) 文件夹是否是用户想要的文件夹之一
B)对于该文件夹中的每个项目都是一个目录或一个文件
zipf.getinfo(name).is_dir()
您也可以使用 infolist
而不是 namelist
来直接获取 ZipInfo 对象而不是名称。
或者,检查名称 - 目录将以 /
结尾。 (这与 is_dir
执行的检查相同。)
这是我目前的系统,它只是查看路径中是否有句点...但这并不适用于所有情况
with ZipFile(zipdata, 'r') as zipf: #Open the .zip BytesIO in Memory
mod_items = zipf.namelist() #Get the name of literally everything in the zip
for folder in mod_folders:
mod_items.insert(0, folder)
#Put the folder at the start of the list
#This makes sure that the folder gets created
#Search through every file in the .zip for each folder indicated in the save
for item in mod_items:
if folder in item: #If the item's path indicates that it is a member of the folder
itempath = item #Make a copy of the
if not itempath.startswith(folder):
itempath = path_clear(itempath, folder)
if not 'GameData/' in itempath:
itempath = 'GameData/' + itempath
path = mod_destination_folder + '/' + itempath
path = path_clear(path)
dot_count = path.count('.')
if dot_count: #Is a normal file, theoretically
itemdata = zipf.read(item)
try:
with open(path, 'wb') as file:
file.write(itemdata)
except FileNotFoundError as f:
folder_path = path[:path.rfind('/')]
makedirs(folder_path)
with open(path, 'wb') as file:
file.write(itemdata)
else: #Is a folder
try: makedirs(path)
except: pass
我只需要某种方法来确定是否: A) 文件夹是否是用户想要的文件夹之一 B)对于该文件夹中的每个项目都是一个目录或一个文件
zipf.getinfo(name).is_dir()
您也可以使用 infolist
而不是 namelist
来直接获取 ZipInfo 对象而不是名称。
或者,检查名称 - 目录将以 /
结尾。 (这与 is_dir
执行的检查相同。)