【问题标题】:How do I read line by line a text file in ruby (hosting it on s3)?如何在 ruby​​ 中逐行读取文本文件(将其托管在 s3 上)?
【发布时间】:2011-08-14 02:59:42
【问题描述】:

我知道我以前做过这个并找到了一组简单的代码,但我不记得或找不到它:(。

我有一个要导入 Rails 3 应用程序的记录文本文件。

每一行代表一条记录。可能它可能是属性的制表符分隔,但也可以只使用一个值。

我该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby text import heroku


    【解决方案1】:

    你想要IO.foreach:

    IO.foreach('foo.txt') do |line|
      # process the line of text here
    end
    

    或者,如果它确实是制表符分隔的,您可能想要使用CSV 库:

    File.open('foo.txt') do |f|
      CSV.foreach(f, col_sep:"\t") do |csv_row|
        # All parsed for you
      end
    end
    

    【讨论】:

    • IO.foreach 是否提供迭代器?
    【解决方案2】:
      IO.foreach("input.txt") do |line| 
        out.puts line
        # You might be able to use split or something to get attributes
        atts = line.split
      end
    

    【讨论】:

      【解决方案3】:
      File.open("my/file/path", "r").each_line do |line|
        # name: "Angela"    job: "Writer"    ...
        data = line.split(/\t/)
        name, job = data.map{|d| d.split(": ")[1] }.flatten
      end
      

      相关话题

      What are all the common ways to read a file in Ruby?

      【讨论】:

      • 这并不能解决文件在 s3 上的问题
      • @Patm,哦,我明白了 :) 但是目前所有三个回答者都在回答这个话题不是关于 S3 的。只是How do I read line by line a text file in ruby
      • 当文件位于 s3 中时有没有办法这样做?
      • @Angela File.open("在此处插入网址")
      • 这是否正确关闭了文件?
      【解决方案4】:

      您是否尝试过使用OpenURI (http://ruby-doc.org/stdlib-2.1.2/libdoc/open-uri/rdoc/OpenURI.html)?您必须让您的文件可以从 S3 访问。

      或者尝试使用 de aws-sdk gem (http://aws.amazon.com/sdk-for-ruby)。

      【讨论】:

      • 文件将具有权限,但我想它仍然需要能够使用顶部的答案使用 File 类来通过它,我不清楚它是否可以。
      【解决方案5】:

      您可以使用OpenURI 读取远程或本地文件。

      假设你的模型有一个名为file的附件:

      # If object is stored in amazon S3, access it through url
      file_path = record.file.respond_to?(:s3_object) ? record.file.url : record.file.path
      open(file_path) do |file|
        file.each_line do |line|
          # In your case, you can split items using tabs
          line.split("\t").each do |item|
            # Process item
          end
        end
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-21
        • 2022-11-05
        • 1970-01-01
        • 2014-12-01
        • 2015-10-25
        • 2011-07-23
        • 2012-10-11
        • 1970-01-01
        相关资源
        最近更新 更多