如何在 Ruby 中创建文件 [英] How to create a file in Ruby
本文介绍了如何在 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
这发生在 IRB 和 Ruby 脚本中.我错过了什么?
This happens from IRB as well as a Ruby script. What am I missing?
推荐答案
使用:
File.open("out.txt", [your-option-string]) {|f| f.write("write your stuff here") }
您的选择:
r
- 只读.该文件必须存在.w
- 创建一个空文件用于写入.a
- 附加到文件.如果文件不存在,则创建该文件.r+
- 打开一个文件进行读写更新.该文件必须存在.w+
- 创建一个用于读写的空文件.a+
- 打开一个文件进行读取和追加.如果文件不存在,则创建该文件.
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.
在您的情况下,'w'
更可取.
In your case, 'w'
is preferable.
或者你可以:
out_file = File.new("out.txt", "w")
#...
out_file.puts("write your stuff here")
#...
out_file.close
这篇关于如何在 Ruby 中创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文