Hi, Is there a way to extract the content of a zip file with GDScript? I don't want to read from within the zip file, I want to extract the content of the zip file and then read from it, is it possible?
Extracting the content of a zip file
It seems there is currently in built-in way to pack or unpack zip files in Godot according to this open GitHub issue. It seems there is a pull request to expose the minizip API Godot uses to GDScript, but it hasn't been merged.
You might be able to build a GDNative plugin for unpacking zip files though, but I have no idea how easy/hard it would be do to.
I found a way, I use Gdunzip.gd to read the content of the zip file, but I don't use it to extract because it is too slow, so for extraction I use this script (see attached text file just change the name to unzip.gd) .
the usage is like this:
var Unzip = load('res://addons/gdunzip/unzip.gd').new()
Unzip.unzip("zip file path","destination of extraction path")
you can also use resources in a zip file like this:
ProjectSettings.load_resource_pack("zip file path")
var data = load("import/x.tscn").instance()
add_child(data)
but I was looking for a way to unzip a zip file, not just read it's content, so the above way is the solution.
here is the code for the file it didn't upload (the name should be unzip.gd):
var storage_path
var zip_file
func unzip(sourceFile,destination):
zip_file = sourceFile
storage_path = destination
var gdunzip = load('res://addons/gdunzip/gdunzip.gd').new()
var loaded = gdunzip.load(zip_file)
if !loaded:
print('- Failed loading zip file')
return false
ProjectSettings.load_resource_pack(zip_file)
var i = 0
for f in gdunzip.files:
unzip_file(f)
func unzip_file(fileName):
var readFile = File.new()
if readFile.file_exists("res://"+fileName):
readFile.open(("res://"+fileName), File.READ)
var content = readFile.get_buffer(readFile.get_len())
readFile.close()
var base_dir = storage_path + fileName.get_base_dir()
var dir = Directory.new()
dir.make_dir(base_dir)
var writeFile = File.new()
writeFile.open(storage_path + fileName, File.WRITE)
writeFile.store_buffer(content)
writeFile.close()
```
- Edited
Thanks for sharing this!
The unzipping works very well.
However, the following line causes trouble:
ProjectSettings.load_resource_pack(zip_file)
Because later on in the game, I need to list all items of a directory, using the following.
func ListItemsInDirectory(path):
var items = []
var dir = Directory.new()
dir.open(path)
dir.list_dir_begin(true, false)
while true:
var file = dir.get_next()
if file == "":
break
items.append(file)
dir.list_dir_end()
return items
But every time get_next() is used, it returns a file name that was inside zip_file, and then the next in that zip_file etc.
Also, things like this don't work anymore:
Directory.remove("path/to/file")
How can I get Godot to stop looking at that zip_file?