【问题标题】:Issue with writing data into an existing CSV file using ruby使用 ruby​​ 将数据写入现有 CSV 文件的问题
【发布时间】:2013-04-19 01:18:40
【问题描述】:

test1.csv

yearID,teamID,lgID,playerID,salary
1985,BAL,AL,boddimi01,625000
1985,BAL,AL,dauerri01,480000
1985,BAL,AL,davisst02,437500
1986,BAL,AL,dempsri01,512500
1986,BAL,AL,dwyerji01,375000
1987,BAL,AL,flanami01,641667

这是我的红宝石代码!

File.foreach('test1.csv') do |csv_line|
    row = CSV.parse_line(csv_line)
    
    if File.exist?("year_#{row[0]}_info.csv")
        File.open("year_#{row[0]}_info.csv", 'w') do |f|     
            f.write("\n#{row[4]}")   
        end
    else
        File.open("year_#{row[0]}_info.csv", 'w') do |f|     
            f.write("#{row[4]}")   
        end
    end
end

我正在尝试获得以下输出之一

#year_1985_info.csv
625000
480000
437500

但我只得到这个输出

#year_1985_info.csv

437500

如何获得所需的输出?

提前非常感谢!

【问题讨论】:

    标签: ruby file csv fwrite


    【解决方案1】:

    您需要以“追加”模式打开文件。像这样:

    File.open("year_#{row[0]}_info.csv", 'a')
    

    注意“a”。

    【讨论】:

    • 感谢您的回答。我从 w 更改为 w+,但输出没有改变。
    • 我的错!你实际上需要'a'模式。我正在更新答案。我刚刚在我的机器上测试了它,它适用于“a”模式。
    【解决方案2】:

    不断打开和关闭同一个文件效率很低。

    我要做的是按年份对它们进行分组,然后一次将它们打印到每个文件中。

    scores = CSV.read('test1.csv').drop(1) #drop header line
    grouped = scores.group_by(&:first)     #group by year
    
    grouped.each do |year, rows|
      File.open("year_#{year}_info.csv", "w") do |f|
        f.puts rows.map(&:last)  #just want last column
      end
    end
    

    【讨论】:

      【解决方案3】:

      如果文件存在,你想追加而不是创建一个空文件:

      require 'csv'
      
      File.foreach('test1.csv') do |csv_line|
        row = CSV.parse_line(csv_line)
      
        ofname = "year_#{row[0]}_info.csv";
        if File.exist?(ofname)
          File.open(ofname, 'a') do |f|       # Note the 'a' here
            f.write("\n#{row[4]}")
          end
        else
          File.open(ofname, 'w') do |f|
            f.write("#{row[4]}")
          end
        end
      end
      

      我实际上认为在每行末尾都有一个换行符会更好;这使 CSV 文件更易于使用。它还简化了您的代码:

      require 'csv'
      
      File.foreach('test1.csv') do |csv_line|
        row = CSV.parse_line(csv_line)
      
        File.open("year_#{row[0]}_info.csv", 'a') do |f|
          f.write("#{row[4]}\n")
        end
      end
      

      请注意,'a' 实际上可以用于创建或附加。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-29
        • 2021-05-27
        • 2013-04-01
        • 1970-01-01
        • 2016-08-22
        • 1970-01-01
        • 2015-12-10
        • 1970-01-01
        相关资源
        最近更新 更多