3
3

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でCSVのURLから画像をダウンロードする

Last updated at Posted at 2016-01-08

Ruby標準ライブラリCSVを使用

リファレンス
要約

CSV (Comma Separated Values) を扱うライブラリです。

投入用のサンプルCSV

data.csv
id,url
1,http/example.com/foo.png
2,http/example.com/bar.png
3,http/example.com/foobar.png

CSVファイルと同じディレクトリにsave_image.rbを配置して実行

save_image.rb
require 'CSV'
require 'open-uri'

def save_image
  table = CSV.table('data.csv')
  save_dir = 'path/to/images/'

  # create directory,if not exist.
  FileUtils.mkdir_p(save_dir) unless FileTest.exist?(save_dir)

  table.each do |row|
    @url = row.field(:url)
    file_name = File.basename(@url).chomp
    file_path = save_dir + file_name
    
    open(file_path,'wb') do |output|
      open(@url) do |data|
        output.write(data.read)
      end
    end
  end
end

保存先に指定したディレクトリに画像がダウンロードされてたら完了です
CSVライブラリ最高です

3
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?