【发布时间】:2011-02-16 04:39:58
【问题描述】:
我需要从数据库中读取数据,然后将其保存在文本文件中。
如何在 Ruby 中做到这一点? Ruby 中有没有文件管理系统?
【问题讨论】:
我需要从数据库中读取数据,然后将其保存在文本文件中。
如何在 Ruby 中做到这一点? Ruby 中有没有文件管理系统?
【问题讨论】:
你可以使用短版:
File.write('/path/to/file', 'Some glorious content')
它返回写入的长度;有关更多详细信息和选项,请参阅::write。
要附加到文件,如果它已经存在,使用:
File.write('/path/to/file', 'Some glorious content', mode: 'a')
【讨论】:
要销毁文件之前的内容,然后在文件中写入一个新的字符串:
open('myfile.txt', 'w') { |f| f << "some text or data structures..." }
附加到文件而不覆盖其旧内容:
open('myfile.txt', "a") { |f| f << 'I am appended string' }
【讨论】:
Ruby File class 将为您提供::new 和::open 的来龙去脉,但它的父级IO class 深入了解#read 和#write。
【讨论】:
在大多数情况下这是首选方法:
File.open(yourfile, 'w') { |file| file.write("your text") }
当一个块被传递给File.open时,文件对象将在块终止时自动关闭。
如果您不将块传递给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
你可以在documentation找到它:
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.openblog.rubybestpractices.com/posts/rklemme/… 在官方文档中也提到了
对于我们这些通过例子学习的人......
像这样将文本写入文件:
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
【讨论】:
IO.write 选项覆盖文件内容而不是追加。附加 IO.write 有点繁琐。
Errno::ENOENT: No such file or directory @ rb_sysopen 消息和创建的大小为 0 字节的文件。
Zambri的回答found here是最好的。
File.open("out.txt", '<OPTION>') {|f| f.write("write your stuff here") }
<OPTION> 的选项在哪里:
r - 只读。该文件必须存在。
w - 创建一个空文件用于写入。
a - 附加到文件。如果文件不存在,则创建该文件。
r+ - 打开一个文件以更新读写。该文件必须存在。
w+ - 为读写创建一个空文件。
a+ - 打开一个文件进行读取和附加。如果文件不存在,则创建该文件。
在您的情况下,w 更可取。
【讨论】:
您在寻找以下内容吗?
File.open(yourfile, 'w') { |file| file.write("your text") }
【讨论】:
yourfile 是一个保存要写入的文件名的变量。
f.write 引发异常,文件描述符将保持打开状态。
File.write('filename', 'content')
IO.write('filename', 'content')