Ruby 如何在文件中添加新行
我想在下面添加换行符。 但结果是错误的。 教我怎么回事Ruby 如何在文件中添加新行,ruby,Ruby,我想在下面添加换行符。 但结果是错误的。 教我怎么回事 f = File.open("test.txt","r+") f.each{|line| if line.include?("2014-10") f.puts nil end } f.close test.txt(之前) test.txt(之后) 我在下面编写了一个ruby脚本,但结果是错误的 f = File.open("test.txt","r+") f.each{|line| if line.include?(
f = File.open("test.txt","r+")
f.each{|line|
if line.include?("2014-10")
f.puts nil
end
}
f.close
test.txt(之前)
test.txt(之后)
我在下面编写了一个ruby脚本,但结果是错误的
f = File.open("test.txt","r+")
f.each{|line|
if line.include?("2014-10")
f.puts nil
end
}
f.close
结果
------------------
2014-09
2014-10
014-11
------------------
要解决您的问题,最简单的方法是创建一个新文件,将新文本输出到其中。为此,您需要打开输入文件和输出文件,并迭代文件的每一行,检查条件并将所需的行放入输出文件中 范例
require 'fileutils'
File.open("text-output.txt", "w") do |output|
File.foreach("text.txt") do |line|
if line.include?("2014-10")
output.puts line + "\n"
else
output.puts line
end
end
end
FileUtils.mv("text-output.txt", "text.txt")
捷径
File.write(f = "text.txt", File.read(f).gsub(/2014-10/,"2014-10\n"))
同时读取和写入文件可能会变得混乱,对于数组等其他数据结构也是如此。您应该在进行过程中构建一个新文件 一些注意事项:
- 您应该使用
的块形式,因为它可以防止您忘记调用File.open
f.close
与没有参数的put nil
相同put
- 当不需要字符串插值时,单引号优于双引号
- 您应该使用
而不是{…}do。。。对于多行块,结束
都可以替换为File.open(…)。每个
File.foreach
- 中间结果可以存储在
对象中,该对象将响应StringIO
等put
require 'stringio'
file = 'test.txt'
output = StringIO.new
File.foreach(file) do |line|
if line.include? '2014-10'
output.puts
else
output << line
end
end
output.rewind
File.open(file, 'w') do |f|
f.write output.read
end
需要“stringio”
文件='test.txt'
输出=StringIO.new
File.foreach(File)do |行|
如果行,包括吗?”2014-10'
输出.puts
其他的
输出检查此选项而不是f.puts
尝试f.write“\n”
@takuma-您能在此处输入预期的o/p吗?您正在用nil
覆盖字符2
。仅仅添加一个字符似乎需要做很多工作,但是创建一个新文件是最容易的。您可以通过以下两种方式之一实现此目的。您可以将整个文件读入一个字符串,关闭该文件,在内存中修改该字符串,并将该字符串写入具有相同名称的文件,从而覆盖原始文件。第二种方法是将文件的每一行读入字符串,修改字符串并将修改后的字符串写入具有不同名称的文件。完成后,关闭两个文件,删除第一个文件,并将第二个文件重命名为旧文件名。
require 'stringio'
file = 'test.txt'
output = StringIO.new
File.foreach(file) do |line|
if line.include? '2014-10'
output.puts
else
output << line
end
end
output.rewind
File.open(file, 'w') do |f|
f.write output.read
end