FasterCSV: Read Remote CSV Files

℡╲_俬逩灬. 提交于 2020-01-02 07:03:02

问题


I can't seem to get this to work. I want to pull a CSV file from a different webserver to read in my application. This is how I'd like to call it:

url = 'http://www.testing.com/test.csv'
records = FasterCSV.read(url, :headers => true, :header_converters => :symbol)

But that doesn't work. I tried Googling, and all I came up with was this excerpt: Practical Ruby Gems

So, I tried modifying it as follows:

require 'open-uri'
url = 'http://www.testing.com/test.csv'
csv_url = open(url)
records = FasterCSV.read(csv_url, :headers => true, :header_converters => :symbol)

... and I get a can't convert Tempfile into String error (coming from the FasterCSV gem).

Can anyone tell me how to make this work?


回答1:


require 'open-uri'
url = 'http://www.testing.com/test.csv'
open(url) do |f|
  f.each_line do |line|
    FasterCSV.parse(line) do |row|
      # Your code here
    end
  end
end

http://www.ruby-doc.org/core/classes/OpenURI.html http://fastercsv.rubyforge.org/




回答2:


I would retrieve the file with Net::HTTP for example and feed that to FasterCSV

Extracted from ri Net::HTTP

 require 'net/http'
 require 'uri'

 url = URI.parse('http://www.example.com/index.html')
 res = Net::HTTP.start(url.host, url.port) {|http|
   http.get('/index.html')
 }
 puts res.body



回答3:


You just had a small typo. You should have used FasterCSV.parse instead of FasterCSV.read:

data = open('http://www.testing.com/test.csv')
records = FasterCSV.parse(data)



回答4:


I would download it with rio - as easy as:

require 'rio'
require 'fastercsv'

array_of_arrays = FasterCSV.parse(rio('http://www.example.com/index.html').read)



回答5:


I upload CSV file with Paperclip and save it to Cloudfiles and then start file processing with Delayed_job.

This worked for me:

require 'open-uri'
url = 'http://www.testing.com/test.csv'
open(url) do |file|
  FasterCSV.parse(file.read) do |row|
    # Your code here
  end
end


来源:https://stackoverflow.com/questions/435634/fastercsv-read-remote-csv-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!