[ruby] How to create a file in Ruby

I'm trying to create a new file and things don't seem to be working as I expect them too. Here's what I've tried:

File.new "out.txt"
File.open "out.txt"
File.new "out.txt","w"
File.open "out.txt","w"

According to everything I've read online all of those should work but every single one of them gives me this:

ERRNO::ENOENT: No such file or directory - out.txt

This happens from IRB as well as a Ruby script. What am I missing?

This question is related to ruby file io errno

The answer is


You can also use constants instead of strings to specify the mode you want. The benefit is if you make a typo in a constant name, your program will raise an runtime exception.

The constants are File::RDONLY or File::WRONLY or File::CREAT. You can also combine them if you like.

Full description of file open modes on ruby-doc.org


If the objective is just to create a file, the most direct way I see is:

 FileUtils.touch "foobar.txt"

OK, now I feel stupid. The first two definitely do not work but the second two do. Not sure how I convinced my self that I had tried them. Sorry for wasting everyone's time.

In case this helps anyone else, this can occur when you are trying to make a new file in a directory that does not exist.


File.new and File.open default to read mode ('r') as a safety mechanism, to avoid possibly overwriting a file. We have to explicitly tell Ruby to use write mode ('w' is the most common way) if we're going to output to the file.

If the text to be output is a string, rather than write:

File.open('foo.txt', 'w') { |fo| fo.puts "bar" }

or worse:

fo = File.open('foo.txt', 'w')
fo.puts "bar"
fo.close

Use the more succinct write:

File.write('foo.txt', 'bar')

write has modes allowed so we can use 'w', 'a', 'r+' if necessary.

open with a block is useful if you have to compute the output in an iterative loop and want to leave the file open as you do so. write is useful if you are going to output the content in one blast then close the file.

See the documentation for more information.


Try using "w+" as the write mode instead of just "w":

File.open("out.txt", "w+") { |file| file.write("boo!") }

data = 'data you want inside the file'.

You can use File.write('name of file here', data)


The directory doesn't exist. Make sure it exists as open won't create those dirs for you.

I ran into this myself a while back.


Try

File.open("out.txt", "w") do |f|     
  f.write(data_you_want_to_write)   
end

without using the

File.new "out.txt"

Examples related to ruby

Uninitialized Constant MessagesController Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Ruby - ignore "exit" in code Empty brackets '[]' appearing when using .where find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException) How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite? How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? How to update Ruby with Homebrew?

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to io

Reading file using relative path in python project How to write to a CSV line by line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder Exception: Unexpected end of ZLIB input stream How to get File Created Date and Modified Date Printing Mongo query output to a file while in the mongo shell Load data from txt with pandas Writing File to Temp Folder How to get resources directory path programmatically ValueError : I/O operation on closed file

Examples related to errno

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv' MySQL: Error dropping database (errno 13; errno 17; errno 39) Python socket.error: [Errno 111] Connection refused How to create a file in Ruby Cannot assign requested address - possible causes? Python [Errno 98] Address already in use How to know what the 'errno' means?