Ruby - How to write a new file with output from script
Outputting to a new file can be done like this (don't forget the second parameter):
output = File.open( "outputfile.yml","w" )
output << "This is going to the output file"
output.close
So in your example, you could do this :
File.open("us_cities.yml", "r+") do |file|
while line = file.gets
"do find a replace"
end
output = File.open( "outputfile.yml", "w" )
output << "Here I am writing to a new file"
output.close
end
If you want to append to the file, make sure you put the opening of the output file outside of the loop.
How to create a file in Ruby
Use:
File.open("out.txt", [your-option-string]) {|f| f.write("write your stuff here") }
where your options are:
r
- Read only. The file must exist.w
- Create an empty file for writing.a
- Append to a file.The file is created if it does not exist.r+
- Open a file for update both reading and writing. The file must exist.w+
- Create an empty file for both reading and writing.a+
- Open a file for reading and appending. The file is created if it does not exist.
In your case, 'w'
is preferable.
OR you could have:
out_file = File.new("out.txt", "w")
#...
out_file.puts("write your stuff here")
#...
out_file.close
How to write to file in Ruby?
The Ruby File class will give you the ins and outs of ::new
and ::open
but its parent, the IO class, gets into the depth of #read
and #write
.
How do I save the text of puts in Ruby to a txt file?
There are ways to save the output of a script to a file without having to modify every puts
in the script.
The easiest is to route the output at the command-line using redirection. Running a script with > some_file
at the of the command will route all STDOUT to the file. Similarly, using > some_file 2>&1
will route both STDOUT and STDERR to the same file. This won't capture anything typed in at a gets
as the code waits for input though, because that won't count as program output.
If you don't mind changing your code a little, you can temporarily change the interpreter's idea of what STDOUT is by reassigning it to a file:
old_stdout = $stdout
File.open('output.txt', 'w') do |fo|
$stdout = fo
# ----
# your code goes here
puts "hello world"
# ----
end
$stdout = old_stdout
Run that, then look at the file "output.txt" and you'll see "hello world", even though we didn't print to the file-handle fo
directly, like we would normally do using fo.puts
.
There are a variety of ways of doing the same thing but they amount to pointing STDOUT or STDERR somewhere else, writing to them, then resetting them.
Typically, if we intend from the start to output to a file, then we should use a File.open
block:
File.open('output.txt', 'w') do |fo|
fo.puts "hello world"
end
The benefit of that is the file will be closed automatically when the block exits.
How do I write to a file in Ruby?
The correct way:
file = File.join(File.dirname(__FILE__), 'test.txt')
File.open(file, 'w') { |f| f.puts 'hello' }
__FILE__
is the path to the file containing the above code, and since, your test.txt
resides in the same directory as write_to_file.rb
, this should work, regardless of which directory you are in, on your machine.
Also, note that, I have used puts
method instead of write
, since I prefer newlines. :)
Whats wrong with your Code (probably):
When you use test.txt
, then the path is relative to the directory from where you are running your write_to_file.rb
script. For example, if you run write_to_file.rb
from your home directory, then test.txt
will imply ~/test.txt
.
How to write output file of ruby code into specific directory/location?
Because \
in strings are special characters so you should use \\
(double backslashes) to get a single backslash. But there is a better way, you don't need to deal with backslashes at all:
fname = File.join("C:", "repo", "cookbooks", "abc", "recipes", "add.rb")
How to print output of ruby function to a file
The problem is that ./program.rb > output.txt
redirects the output as well as the prompts for input into the text file, so you can't see what you're doing. You have several options:
- Use
STDERR.puts
to prompt for input, so it doesn't get caught by the redirection. This is my preferred method. - Use
ARGV
to pass input to your program. This is a good option if you think the program isn't too hard to use without prompts. - Use
File.open
to create an output file and write to it directly. Sometimes this is the most sensible option, but usually you want to do one of the first two.
Write Ruby Output to a File
Just change variable name f
to ff
, and do:
entry = nil
if mod > (Time.now - 86400)
found_completed = true
entry = "#{modtime} - #{project} - #{wordcount}"
end
open('/path/to/newfile.txt', 'a+') {|ff| ff.puts entry }
or:
if mod > (Time.now - 86400)
found_completed = true
entry = "#{modtime} - #{project} - #{wordcount}"
open('/path/to/newfile.txt', 'a+') {|ff| ff.puts entry }
end
To open file for write/read operations, and then to use it, do:
fstore = open '/path/to/newfile.txt', 'a+'
...
fstore.puts entry
...
fstore.close
Ruby redirect output to file
You either can write to a file explicitly (open file and write to it)
file = File.open('target.file', 'w') do |file|
File.foreach('links.txt') do |li|
file.puts(li) if li['PersonNight']
end
end
Or redirect from outside your script, using regular unix machinery
ruby my_script.rb > target.file
Related Topics
How to Write a Rails Mixin That Spans Across Model, Controller, and View
What Does "No Binary Rubies Available" Mean
Set Tag Attribute and Add Plain Text Content to the Tag Using Nokogiri Builder (Ruby)
Ending a Rails 2 Url with an Ip Address Causes Routing Error
Add a Callback Function to a Ruby Array to Do Something When an Element Is Added
How to Get a Remote-File's Mtime Before Downloading It in Ruby
Error Installing Gem: Couldn't Reserve Space for Cygwin's Heap, Win32 Error 487
Postgres Range Fields + Rails Forms
Trying to Understand Use of Self.Method_Name VS. Classname.Method_Name in Ruby
Ruby - How to Write a New File with Output from Script
How to Sort Not Simple Hash (Hash of Hashes)
Comma Separated Array with a Text_Field in Rails
Read Contents of a Local File into a Variable in Rails