Ruby:检查.zip文件是否存在,然后解压缩

时间:2014-01-17 00:12:06

标签: ruby

2个小问题,以创造我正在寻找的效果。 如何检查扩展名为.zip的目录中是否存在文件? 如果确实存在,我需要创建一个与.zip同名但没有该文件夹的.zip扩展名的文件夹。 然后我需要将文件解压缩到文件夹中。

其次,如果文件夹中有多个.zip文件,该怎么办?

我正在做这样的事情并试图把它放进红宝石

`mkdir fileNameisRandom`
`unzip fileNameisRandom.zip -d fileNameisRandom`

在类似的帖子中我发现了类似

的内容
Dir.entries("#{Dir.pwd}").select {|f| File.file? f}
我知道

检查目录中的所有文件并确保它们是文件。 问题是我不知道如何确保它只是.zip

的扩展名

另外,我找到了Glob函数来检查文件名的扩展名:http://ruby-doc.org/core-1.9.3/Dir.html 在这种情况下如何确保文件存在,如果不存在,我可以打印出错误。

来自我现在的评论

if Dir['*.zip'].first == nil #check to see if any exist
    puts "A .zip file was not found"
elsif Dir['*.zip'].select {|f| File.file? f} then #ensure each of them are a file
    #use a foreach loop to go through each one
    Dir['*.zip'].select.each do |file|
        puts "#{file}"
    end  ## end for each loop
end

2 个答案:

答案 0 :(得分:4)

这是一种使用较少分支的方法:

# prepare the data
zips= Dir['*.zip'].select{ |f| File.file? } 

# check if data is sane
if zips.empty?
  puts "No zips"
  exit 0 # or return
end

# process data   
zips.each do |z|

end

这种模式对于其他程序员来说更容易理解。

您也可以使用名为rubyzip

的红宝石宝石来完成此操作

的Gemfile:

source 'https://rubygems.org'
gem 'rubyzip'

运行捆绑

unzip.rb:

require 'zip'

zips= Dir['*.zip'].select{ |f| File.file? } 

if zips.empty?
  puts "No zips"
  exit 0 # or return
end

zips.each do |zip|
  Zip::File.open(zip) do |files|
    files.each do |file|
       # write file somewhere 
       # see here https://github.com/rubyzip/rubyzip
    end
  end
end

答案 1 :(得分:0)

我最终将教程中的不同信息拼凑在一起,并使用@rogerdpack和他的评论寻求帮助。     需要'rubygems / package'     #require'zlib'     要求'fileutils'

#move to the unprocessed directory to unpack the files
#if a .tgz file exists
#take all .tgz files
#make a folder with the same name
#put all contained folders from .tgz file inside of similarly named folder
#Dir.chdir("awaitingApproval/")


if Dir['*.zip'].first == nil #check to see if any exist, I use .first because Dir[] returns an array
    puts "A .zip file was not found"
elsif Dir['*.zip'].select {|f| File.file? f} then #ensure each of them are a file
    #use a foreach loop to go through each one
    Dir['*.zip'].select.each do |file|
        puts "" #newlie for each file
        puts "#{file}" #print out file name
        #next line based on `mkdir fileNameisRandom`
        `mkdir #{Dir.pwd}/awaitingValidation/#{ File.basename(file, File.extname(file)) }`
        #next line based on `unzip fileNameisRandom.zip -d fileNameisRandom`
        placement = "awaitingValidation/" + File.basename(file, File.extname(file))
        puts "#{placement}"
        `sudo unzip #{file} -d #{placement}`
        puts "Unzip complete"
    end  ## end for each loop
end
相关问题