如何在Ruby中关闭和删除文件? [英] How to close and delete a file in Ruby?

查看:159
本文介绍了如何在Ruby中关闭和删除文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我像这样在Ruby中打开文件:

Say that I open a file in Ruby like this:

f = File.open('diagram.txt', 'r')

现在,为了关闭和删除该文件,我有以下代码:

Right now, in order to close and delete that file I have this code:

begin
  f = File.open('diagram.txt', 'r')
ensure
  if !f.nil? && File.exist?(f)
    f.close unless f.closed? 
    File.delete(f)
  end
end

我发现这段代码太复杂了,如果f已经关闭,File.exist?(f)将会失败.那么,避免关闭和删除引起异常的文件的正确方法是什么?

I found this code to be too complicated, and the File.exist?(f) would fail if the f is closed already. So, what is the correct approach to avoid the closing and deleting of the file raising exceptions?

注意:我知道将一个块传递给File.open会直接关闭文件,但是,我正在寻找关闭和删除文件的一般方法.

Note: I know that passing a block to File.open will close the file directly, however, I am looking for the general approach of closing and deleting.

推荐答案

处理Errno :: ENOENT异常

由于不能保证示例代码中不存在 diagram.txt 文件,因此,更大的问题是处理 Errno :: ENOENT 异常.您可以自动关闭 File#open 阻止,然后在尝试打开或删除丢失的文件时使用救援处理异常.例如:

Handling the Errno::ENOENT Exception

Since your diagram.txt file is not guaranteed to exist in your example code, your bigger problem is handling the Errno::ENOENT exception. You can Call File#open in a self-closing block, and then use rescue to handle the exception if you try to open or delete a missing file. For example:

begin
  File.open('diagram.txt', 'r') do |f|
    # do something with file
    File.delete(f)
  end
rescue Errno::ENOENT
end

这篇关于如何在Ruby中关闭和删除文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆