我正在尝试将我“获取”的数据导出到一个新的 csv 文件中。目前,我下面的代码将每个人都发布到一行,直到它填满,然后继续到下一行。 我希望在导入数据时将其放置在以下行中,创建交易列表。
def export_data
File.open('coffee_orders.csv', 'a+') do |csv|
puts @item_quantity = [Time.now, @item_name, @amount]
csv << @item_quantity
end
end
最佳答案
根据您的起始代码,我会做类似的事情:
def export_data
File.open('coffee_orders.csv', 'a') do |csv|
csv << [Time.now, @item_name, @amount].join(', ')
end
end
或者:
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
请注意,不必使用 'a+'
附加到文件。而是仅使用 'a'
除非您在文件打开时绝对需要“读取”模式。这是 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
这使用 Ruby 的 CSV 类来处理所有来龙去脉。它检查文件是否已经存在,如果没有内容,则在写入内容之前先写入 header 。
关于ruby - 将数据解析为新行上的 csv 文件 - ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20208354/