Files and Directories
Append File
Opening a file in append mode adds text after the existing content.
Append File
append_file.rb
require "tmpdir"
extra_line =
Dir.mktmpdir do |dir|
path = File.join(dir, "log.txt")
File.write(path, "first\nsecond\n")
file = File.open(path, "a")
file.puts extra_line
file.close
lines = File.read(path).split("\n")
puts "file=#{File.basename(path)}"
puts "lines=#{lines.join(",")}"
puts "last=#{lines.last}"
end
require "tmpdir"
extra_line =
Dir.mktmpdir do |dir|
path = File.join(dir, "log.txt")
File.write(path, "first\nsecond\n")
file = File.open(path, "a")
file.puts extra_line
file.close
lines = File.read(path).split("\n")
puts "file=#{File.basename(path)}"
puts "lines=#{lines.join(",")}"
puts "last=#{lines.last}"
end
require "tmpdir"
extra_line =
Dir.mktmpdir do |dir|
path = File.join(dir, "log.txt")
File.write(path, "first\nsecond\n")
file = File.open(path, "a")
file.puts extra_line
file.close
lines = File.read(path).split("\n")
puts "file=#{File.basename(path)}"
puts "lines=#{lines.join(",")}"
puts "last=#{lines.last}"
end
append mode
Append mode keeps existing file content and writes new content at the end.