在Ruby中编辑文件中的每一行 [英] Edit each line in a file in Ruby

查看:169
本文介绍了在Ruby中编辑文件中的每一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找一种编辑文件中每一行的简单方法,而我在理解如何使用文件类时遇到一些麻烦。

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 I want to edit has several hundred lines with comma separated values in each line. I'm only interested in the first value in each line, and I want to delete all values after the first one. I tried to do the following:

File.open('filename.txt', 'r+') do |file|
  file.each_line { |line| line = line.split(",")[0] }
  file.write
  file.close
end

哪个不起作用,因为 File.write 方法需要将内容写成参数。

Which doesn't work because File.write method requires the contents to be written as an argument.

有人可以告诉我如何达到预期的效果吗?

Could someone enlighten me as to how I could achieve the desired effect?

推荐答案

一个更好的解决方案(也是最安全的)是使用 TempFile <创建一个临时文件/ a>,并将其移至原始位置(使用 FileUtils )完成后:

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")

这篇关于在Ruby中编辑文件中的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆