Edit each line in a file in Ruby

后端 未结 5 972
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 02:52

I\'m trying to find a simple way of editing each line in a file, and I\'m having some trouble understanding how to use the File class to do so.

The file

5条回答
  •  眼角桃花
    2020-12-14 03:51

    The one of the better solutions(and safest) is to create a temporary file using TempFile, and move it to the original location(using FileUtils) once you are done:

       require 'fileutils'
       require 'tempfile'
    
        t_file = Tempfile.new('filename_temp.txt')
        File.open("filename.txt", 'r') do |f|
          f.each_line{|line| t_file.puts line.split(",")[0].to_s }
        end
        t_file.close
        FileUtils.mv(t_file.path, "filename.txt")
    

提交回复
热议问题