如何从CSV文件中删除行

时间:2015-03-04 18:29:26

标签: ruby csv

我想删除一行并回写该文件。

删除后删除CSV文件的所有内容。

products = {}


def menu
 puts "#{'Item'.ljust(6)} #{'Description'.ljust(10)} #{'Price'.rjust(7)}"
 puts '-' * 4 + '   ' + '-' * 11 + '   ' + '-' * 5
File.open('text.txt').readlines.each do |itemnumber|
puts itemnumber.gsub(/[,]/, '      ')
end
end

user_choice = 0
while user_choice !=8
 puts ''
 puts 'What would you like to do?'
 puts '1: View all products.'
 puts '2: Add a new product.'
 puts '3: Delete a product.'
 puts '4: Update a product.'
 puts '5: View highest priced product.'
 puts '6: View lowest priced product.'
 puts '7: View sum of all products prices.'
 puts '8: Exit.'
 user_choice = gets.chomp.to_i

 if user_choice == 1
  menu
 end


if user_choice == 2
puts ''
puts 'Enter new products description. '
new_products = gets.chomp
puts 'Enter new products price. '
price = gets.chomp.to_f
new_key = rand(100..999)
while products.has_key?(new_key)
  new_key = rand(100..999)
end
puts "#{new_key},#{new_products},#{price}"
open('text.txt', 'a') { |newproduct|
  newproduct.puts "#{new_key},#{new_products},#{price}"
}
end


if user_choice == 3
menu
puts ''
puts "What's the item number you wish to delete?"
item_num = gets.chomp

read_file = File.new('text.txt', "r+").read
write_file = File.new('text.txt', "w+")

read_file.each_line do |line|
  write_file.write(line) unless line.include? item_num
end
end

我做错了什么?在"删除"作为该计划的一部分,我确定存在多种错误。

1 个答案:

答案 0 :(得分:0)

您的删除实际上正在发生,但您当前正在运行的应用程序尚未意识到这一点。

您可以通过重新启动应用和/或查看文本文件来检查。

要解决此问题,在写入文件后,在块中结束,请关闭文件,以便刷新更改:

read_file.each_line do |line|
  write_file.write(line) unless line.include? item_num
end
write_file.close