本文共 1607 字,大约阅读时间需要 5 分钟。
我需要从数据库中读取数据,然后将其保存在文本文件中。
我怎么能在中做到这一点? Ruby中有文件管理系统吗?
在大多数情况下,这是首选方法:
File.open(yourfile, 'w') { |file| file.write("your text") }
当块传递给File.open
,当块终止时,File对象将自动关闭。
如果未将块传递给File.open
,则必须确保正确关闭文件并将内容写入文件。
begin file = File.open("/tmp/some_file", "w") file.write("your text") rescue IOError => e #some error occur, dir not writable etc.ensure file.close unless file.nil?end
您可以在找到它:
static VALUE rb_io_s_open(int argc, VALUE *argv, VALUE klass){ VALUE io = rb_class_new_instance(argc, argv, klass); if (rb_block_given_p()) { return rb_ensure(rb_yield, io, io_close, io); } return io;}
的答案是最好的。
File.open("out.txt", '
<OPTION>
的<OPTION>
是:
r
- 只读。 该文件必须存在。
w
- 创建一个用于写入的空文件。
a
- 附加到文件。如果文件不存在,则创建该文件。
r+
- 打开文件以进行读写更新。 该文件必须存在。
w+
- 为读取和写入创建一个空文件。
a+
- 打开文件进行阅读和追加。 如果文件不存在,则创建该文件。
在你的情况下, w
是更好的。
您可以使用简短版本:
File.write('/path/to/file', 'Some glorious content')
它返回写入的长度; 请参阅以获取更多详细信息和选项。
要附加到文件,如果它已经存在,请使用:
File.write('/path/to/file', 'Some glorious content', mode: 'a')
您在寻找以下内容吗?
File.open(yourfile, 'w') { |file| file.write("your text") }
Ruby 将为您提供::new
和::open
的#read
,但它的父深入到#read
和#write
。
对于我们这些通过实例学习的人......
将文本写入文件,如下所示:
IO.write('/tmp/msg.txt', 'hi')
奖金信息......
像这样读回来
IO.read('/tmp/msg.txt')
通常,我想将文件读入我的剪贴板***
Clipboard.copy IO.read('/tmp/msg.txt')
有时候,我想把剪贴板中的内容写成文件***
IO.write('/tmp/msg.txt', Clipboard.paste)
***假设您已安装剪贴板gem
请参阅: :
要销毁文件的先前内容,请将新字符串写入文件:
open('myfile.txt', 'w') { |f| f << "some text or data structures..." }
要附加到文件而不覆盖其旧内容:
open('myfile.txt', "a") { |f| f << 'I am appended string' }
转载地址:http://sldnb.baihongyu.com/