我正在尝试在Ruby中打开一个简单的CSV文件,找到一个特定的键,将其值增加1,然后重新保存。
CSV文件示例:
store1,0
store2,0
store3,0
...etc.
Ruby代码:
require 'csv'
currentStore = store # store is passed as a parameter
if currentStore.nil? && currentStore.empty?
currentStore = "nil"
store_data = {}
File.open('store_count.csv').each_line {|line|
line_data = line.split(",")
if !line_data[1].nil? && !line_data[1].empty?
store[line_data[0]] = line_data[1].strip.to_i
else
next
end
}
if store_data.key?(currentStore)
store_data[currentStore] += 1
CSV.open("store_count.csv", "wb") {
|csv| store_data.to_a.each {
|elem| csv << elem
}
}
end
例如,如果我增加'store3',我需要我的文件看起来像:
store1,0
store2,0
store3,1
etc...
增加值后,我需要重新保存为CSV。
答案 0 :(得分:0)
你不能同时读写。
What are the Ruby File.open modes and options?
如果您正在处理一个小文件,您可以将所有内容放入内存中,这应该足够了。
temp_file = File.open('temp.csv', 'w')
CSV.readlines('temp.csv').each do |line|
temp_file << "#{line[0]},#{line[1].to_i + 1}\n"
end
temp_file.flush
temp_file.close
如果要重命名文件,可以执行此操作
`rm store.csv`
`mv temp.csv store.csv`