2016-10-13 31 views
0

我想从ZIP包中提取一个单一的内容类型文件到一个尚不存在的目录中。我的代码到目前为止:在不存在的目录中提取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 

该文件夹被成功创建,但没有提取在任何目录下完成。我怀疑工作目录中有什么问题。任何帮助?

回答

1

我相信你忘记打电话给你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) 
+0

谢谢。我怎样才能给任何.ZIP文件分配'zip_file'? –

+0

如果您有一个Zip文件,请将变量'zip_file'的值更改为zip文件的名称(完整路径或相对路径)... –

+0

如果您有多个zip文件需要运行该文件,让我知道,我可以为你更新代码...(如果是这样,是在一个目录中的所有zip文件?)... –