Reputation: 199
I want to extract one single content type file from a ZIP package into a directory that doesn't yet exist. My code so far:
require 'zip'
Dir.mkdir 'new_folder'
#I create the folder
def unzip_file (file_path, destination)
Zip::File.open(file_path) { |zip_file|
zip_file.glob('*.xml'){ |f| #I want to extract .XML files only
f_path = File.join(Preprocess, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
puts "Extract file to %s" % f_path
zip_file.extract(f, f_path)
}
}
end
The folder gets successfully created, but no extraction is done at any directory. I suspect that there is something wrong within the working directory. Any help?
Upvotes: 0
Views: 1145
Reputation: 2984
I believe you forgot to call your unzip
method to begin with...
Nevertheless, this is how I would do this:
require 'zip'
def unzip_file (file_path, destination)
Zip::File.open(file_path) do |zip_file|
zip_file.each do |f| #I want to extract .XML files only
next unless File.extname(f.name) == '.xml'
FileUtils.mkdir_p(destination)
f_path = File.join(destination, File.basename(f.name))
puts "Extract file to %s" % f_path
zip_file.extract(f, f_path)
end
end
end
zip_file = 'random.zip' # change this to zip file's name (full path or even relative path to zip file)
out_dir = 'new_folder' # change this to the name of the output folder
unzip_file(zip_file, out_dir) # this runs the above method, supplying the zip_file and the output directory
EDIT
Adding an additional method called unzip_files
that call unzip_file
on all zipped files in a directory.
require 'zip'
def unzip_file (file_path, destination)
Zip::File.open(file_path) do |zip_file|
zip_file.each do |f| #I want to extract .XML files only
next unless File.extname(f.name) == '.xml'
FileUtils.mkdir_p(destination)
f_path = File.join(destination, File.basename(f.name))
puts "Extract file to %s" % f_path
zip_file.extract(f, f_path)
end
end
end
def unzip_files(directory, destination)
FileUtils.mkdir_p(destination)
zipped_files = File.join(directory, '*.zip')
Dir.glob(zipped_files).each do |zip_file|
file_name = File.basename(zip_file, '.zip') # this is the zipped file name
out_dir = File.join(destination, file_name)
unzip_file(zip_file, out_dir)
end
end
zipped_files_dir = 'zips' # this is the folder containing all the zip files
output_dir = 'output_dir' # this is the main output directory
unzip_files(zipped_files_dir, output_dir)
Upvotes: 1