繁体   English   中英

在不存在的目录中提取ZIP文件

[英]Extracting ZIP files in a directory that doesn't exist

我想从一个ZIP包中提取一个单一的内容类型文件到一个尚不存在的目录中。 到目前为止,我的代码:

  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

该文件夹已成功创建,但在任何目录下均未提取。 我怀疑工作目录内有问题。 有什么帮助吗?

我相信您忘了先调用unzip方法...

不过,这就是我的处理方式:

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

编辑

添加名为unzip_files的其他方法,该方法对目录中所有压缩文件都调用unzip_file

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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