问题描述
我试图找到一种简单的方法来编辑文件中的每一行,但我在理解如何使用 File
类来执行此操作时遇到了一些麻烦.
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,并将其移动到原始位置(使用 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 中编辑文件中的每一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!