I'd like to add a single line to the top a of file with Ruby like this:
# initial file contents
something
else
# file contents after prepending "hello" on its own line
hello
something
else
The following code just replaces the contents of the entire file:
f = File.new('myfile', 'w')
f.write "test string"
Solution: Appending text to a file with Ruby is similar to other languages: you open the file in "append" mode, write your data, and then close the file. Here's a quick example that demonstrates how to append "Hello, world" to a file named myfile. out in the current directory: open('myfile.
"\n" is newline, '\n\ is literally backslash and n.
Here is the another example of opening a file in Ruby. fileObject = File. open("tutorials. txt","r"); print(fileObject.
This is a pretty common task:
original_file = './original_file'
new_file = original_file + '.new'
Set up the test:
File.open(original_file, 'w') do |fo|
%w[something else].each { |w| fo.puts w }
end
This is the actual code:
File.open(new_file, 'w') do |fo|
fo.puts 'hello'
File.foreach(original_file) do |li|
fo.puts li
end
end
Rename the old file to something safe:
File.rename(original_file, original_file + '.old')
File.rename(new_file, original_file)
Show that it works:
puts `cat #{original_file}`
puts '---'
puts `cat #{original_file}.old`
Which outputs:
hello
something
else
---
something
else
You don't want to try to load the file completely into memory. That'll work until you get a file that is bigger than your RAM allocation, and the machine goes to a crawl, or worse, crashes.
Instead, read it line by line. Reading individual lines is still extremely fast, and is scalable. You'll have to have enough room on your drive to store the original and the temporary file.
fwiw this seems to work:
#!usr/bin/ruby
f = File.open("myfile", "r+")
lines = f.readlines
f.close
lines = ["something\n"] + lines
output = File.new("myfile", "w")
lines.each { |line| output.write line }
output.close
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With