3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rubyでzipファイルを展開する方法

Posted at
filename.rb
require 'zip'
require 'fileutils'
require 'byebug'

dest = 'out/'

Zip::File.open('sample.zip') do |zip|#zipファイル開く
  zip.each do |entry|#その中身をentryにひとつずつ渡してゆく
      byebug
    p entry.name#zipファイルの中に入っているファイルの名前(フォルダ名/ファイル名の形式)
        dir = File.join(dest, File.dirname(entry.name))#File.dirname(entry.name)でディレクトリの名前を取得。destと結合
        FileUtils.mkpath(dir)#dir=out/sampleというフォルダを作成
    zip.extract(entry, dest + entry.name) { true }#entryをdest + entry.nameに格納する
  end
end

ポイントは

qiita.rb

dir = File.join(dest, File.dirname(entry.name))#File.dirname(entry.name)でディレクトリの名前を取得。destと結合
FileUtils.mkpath(dir)#dir=out/sampleというフォルダを作成

ここで、先にフォルダを作成してしまうこと。
これがないと、「そのようなディレクトリは見つかりません」エラーがでてしまうことがある

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?