简体   繁体   中英

Extracting ZIP files in a directory that doesn't exist

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM