如果只在ruby中不存在文件时,如何打开文件

我想打开一个文件进行写入,但前提是它尚不存在。 如果文件存在,我想引发exception。 这是最好的方法吗?

filename = 'foo' raise if File.exists? filename File.open(filename, 'w') do |file| file.write contents end 

没有竞争条件,最惯用的方法是什么?

在做了一些进一步的研究后,似乎你可以使用File :: CREAT和File :: EXCL模式标志。

 filename = 'foo' File.open(filename, File::WRONLY|File::CREAT|File::EXCL) do |file| file.write contents end 

在这种情况下,如果文件存在, open将引发exception。 运行一次后,该程序成功运行,没有错误,创建一个名为foo的文件。 在第二次运行时,程序发出以下信息:

 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