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 file. What am I missing?
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
Try
File.open("out.txt", "w") do |f|
f.write(data_you_want_to_write)
end
without using the
File.new "out.txt"
尝试使用w+
作为写入模式,而不仅仅是w
:
File.open("out.txt", "w+") { |file| file.write("boo!") }
链接地址: http://www.djcxy.com/p/25660.html
上一篇: 如何使用Java将字符串保存到文本文件?
下一篇: 如何在Ruby中创建文件