Error in creating new file
When I run this code in irb:
File.open('j1.txt','w') {|f| f.write("doc1223423")}
it works succes开发者_JS百科sfully. But when I do the same in a method in my controller, it gives the following error:
Errno::ENOENT (No such file or directory - file location as specified )
Why does it do that and how do I fix it?
Solved. The above file location that i was specifying didn't exist. I was doing something like this
File.open ("#{RAILS_ROOT}/jatin/j.txt", 'w+') do |f|
f.write("blah")
end
but the directory /jatin/ was not there, so the solution was to first create the directory and then create the file.
Dir::mkdir("#{RAILS_ROOT}/jatin")
Thanks for your help guys.
Try chagning 'w'
to 'w+'
- this will create a new file, 'w'
just opens an existing one for writing (updating).
Here's a good round of examples that might help:
- http://pleac.sourceforge.net/pleac_ruby/fileaccess.html
精彩评论