我正在尝试解析一个远程CSV文件的前5行。但是,当我这样做时,它会引发Errno::ENOENT异常,并说:
No such file or directory - [file contents] (文件内容是CSV内容的转储
下面是我的代码:
def preview
@csv = []
open('http://example.com/spreadsheet.csv') do |file|
CSV.foreach(file.read, :headers => true) do |row|
n += 1
@csv << row
if n == 5
return @csv
end
end
end
end上面的代码是基于我在Stack Overflow上看到的其他人使用的代码构建的,但我无法让它工作。
如果我从文件中删除read方法,它将引发TypeError异常,说明:
can't convert StringIO into String我是不是漏掉了什么?
发布于 2012-08-04 11:52:51
Foreach需要一个文件名。试试parse.each
发布于 2012-08-04 22:01:57
您可以手动将每一行传递给CSV进行解析:
require 'open-uri'
require 'csv'
def preview(file_url)
@csv = []
open(file_url).each_with_index do |line, i|
next if i == 0 #Ignore headers
@csv << CSV.parse(line)
if i == 5
return @csv
end
end
end
puts preview('http://www.ferc.gov/docs-filing/eqr/soft-tools/sample-csv/contract.txt')https://stackoverflow.com/questions/11805459
复制相似问题