Skip to content

Instantly share code, notes, and snippets.

@ruuts
Created April 28, 2020 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruuts/3814459b23ef919cb371255efc5ea5c0 to your computer and use it in GitHub Desktop.
Save ruuts/3814459b23ef919cb371255efc5ea5c0 to your computer and use it in GitHub Desktop.
Download urls from CSV
require 'csv'
require 'optparse'
require 'open-uri'
options = {
file: nil,
column_index: nil
}
parser = OptionParser.new do |opts|
opts.banner = "Usage: import.rb [options]"
opts.on("-f", "--file FILE", "Please provide a csv file") do |val|
options[:file] = val
end
opts.on("-c", "--column-index COLUMN_INDEX", "Index of column that contains url") do |val|
options[:column_index] = val.to_i
end
end
parser.parse!
parser.parse!(%w[--help]) if options.values.any?(&:nil?)
CSV.foreach(options[:file]) do |row|
begin
url = row.delete_at(options[:column_index])
name = row.join('_')
URI.open(url) do |remote_file|
filename = remote_file.base_uri.path.split('/').last
fullname = "#{name}_#{filename}"
open(fullname, 'w') do |local_file|
local_file << remote_file.read
end
end
print '.'
rescue
print 'F'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment