简体   繁体   English

将数据解析为新行上的csv文件 - ruby

[英]Parsing data to a csv file on a new line - ruby

I am trying to export data that I 'get' into a new csv file. 我正在尝试将我得到的数据导出到新的csv文件中。 Currently, my code below posts everyone onto a single line until it fills up and then it continues to the next line. 目前,我的代码将每个人发布到一行,直到它填满,然后继续到下一行。 I would like to have it where when data is imported, it starts on the following line below, creating a list of transactions. 我希望在导入数据的地方,从下面的下一行开始,创建一个事务列表。

def export_data
    File.open('coffee_orders.csv', 'a+') do |csv|
      puts @item_quantity = [Time.now, @item_name, @amount]
      csv << @item_quantity
    end
end

Basing it on your starting code, I'd do something like: 基于你的起始代码,我会做类似的事情:

def export_data
  File.open('coffee_orders.csv', 'a') do |csv|
    csv << [Time.now, @item_name, @amount].join(', ')
  end
end

Or: 要么:

def export_data
  File.open('coffee_orders.csv', 'a') do |csv|
    csv << '%s, %s, %s' % [Time.now, @item_name, @amount].map(&:to_s)
  end
end

Notice, it's not necessary to use 'a+' to append to a file. 请注意,没有必要使用'a+'附加到文件。 Instead use 'a' only unless you absolutely need "read" mode while the file is open also. 而是仅使用'a'除非您在文件打开时绝对需要“读取”模式。 Here's what the IO.new documentation says: 以下是IO.new文档所说的内容:

"a"  Write-only, starts at end of file if file exists,
     otherwise creates a new file for writing.

"a+" Read-write, starts at end of file if file exists,
     otherwise creates a new file for reading and
     writing.

The way I'd write it for myself would be something like: 我为自己写的方式是这样的:

CSV_FILENAME = 'coffee_orders.csv'
def export_data
  csv_has_content = File.size?(CSV_FILENAME)
  CSV.open(CSV_FILENAME, 'a') do |csv|
    csv << %w[Time Item Amount] unless csv_has_content
    csv << [Time.now, @item_name, @amount]
  end
end

This uses Ruby's CSV class to handle all the ins-and-outs. 这使用Ruby的CSV类来处理所有的输入和输出。 It checks to see if the file already exists, and if it has no content it writes the header before writing the content. 它检查文件是否已经存在,如果没有内容,则在写入内容之前写入标题。

Try this. 尝试这个。 It will add a new line after each transaction. 它将在每次交易后添加一个新行。 When you append to it next, it will be from a new line. 当您接下来附加它时,它将来自一个新行。

def export_data
  File.open('coffee_orders.csv', 'a+') do |csv|
    csv.puts @item_quantity = [Time.now, @item_name, @amount]
  end
end

Although by looking the extension, you would probably want to confine it to csv format. 虽然通过查看扩展名,您可能希望将其限制为csv格式。

def export_data
  File.open('coffee_orders.csv', 'a+') do |csv|
    @item_quantity = [Time.now, @item_name, @amount]
    csv.puts @item_quantity.join(',')
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM