仅在ruby中尚不存在的情况下,如何打开文件进行写入 [英] How do open a file for writing only if it doesn't already exist in ruby
问题描述
我想打开一个文件进行写入,但前提是该文件尚不存在.如果文件存在,我想引发一个异常.这是最好的方法吗?
I want to open a file for writing but only if it doesn't already exist. If the file exists I want to raise an exception. Is this the best way to do it?
filename = 'foo'
raise if File.exists? filename
File.open(filename, 'w') do |file|
file.write contents
end
在没有比赛条件的情况下,最惯用的方法是什么?
What is the most idiomatic way to do this without the race condition?
推荐答案
经过进一步研究,似乎可以使用File :: CREAT和File :: EXCL模式标志.
After doing some further research, it seems you can use the File::CREAT and File::EXCL mode flags.
filename = 'foo'
File.open(filename, File::WRONLY|File::CREAT|File::EXCL) do |file|
file.write contents
end
在这种情况下,如果文件存在,则open
将引发异常.运行一次后,该程序成功运行,没有错误,创建了一个名为foo
的文件.在第二次运行时,程序将发出以下消息:
In this case, open
will raise an exception if the file exists. After running once, this program succeeds without error, creating a file named foo
. On the second run, the program emits this:
foo.rb:2:in `initialize': File exists - foo (Errno::EEXIST)
from foo.rb:2:in `open'
from foo.rb:2
来自man open
:
O_WRONLY open for writing only
O_CREAT create file if it does not exist
O_EXCL error if O_CREAT and the file exists
这篇关于仅在ruby中尚不存在的情况下,如何打开文件进行写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!