【问题标题】:How to check for file existence [duplicate]如何检查文件是否存在[重复]
【发布时间】:2012-01-25 06:45:08
【问题描述】:

是否有可以传递“完整路径”home/me/a_file.txt 的 Ruby 类/方法来识别它是否是有效的文件路径?

【问题讨论】:

  • 我的建议是花 10 分钟阅读 FileUtils 和 File 类中的所有方法。从长远来看,它将为您节省大量时间!
  • 您能否澄清您是否想知道“它是否是有效的文件路径”或“它是否是存在的文件的路径”?

标签: ruby file


【解决方案1】:
# file? will only return true for files
File.file?(filename)

# Will also return true for directories - watch out!
File.exist?(filename)

【讨论】:

  • 只是 File.file?应该够了吧?文档:“如果命名文件存在并且是常规文件,则返回 true”
  • 重要的是要注意上面的“and”不是代码:File.exist?(filename) and File.file?(filename) 总是返回 false,因为 File.exist? "如果命名文件是目录,则返回 true,否则返回 false。"
  • 对不起克里斯你错了真假 => 假`>> File.file?('/etc/passwd') => true >> File.file?('/etc/') => false >> File.exists?('/etc/') => true >> File.exists?('/etc/passwd') => true >> File.file?('/etc/passwd')和 File.exists?('/etc/passwd')`
  • 存在吗?现已贬值。
  • @MarkDavies 我的意思不是垃圾邮件,但这个词已被弃用。 stackoverflow.com/questions/9208091/…
【解决方案2】:

查看Pathname,尤其是Pathname#exist?

File 及其FileTest 模块可能更简单/更直接,但我发现Pathname 通常是一个更好的界面。

【讨论】:

  • 感谢 Paul,路径名正是我所需要的。不知何故,我无法找到“文件”和“文件测试”正在接受“完整”路径参数。再次感谢
  • Pathname 非常有用,但不能完全替代 File 和 FileTest。它很容易扩展,因此它确实具有相同的测试,然后它作为包装器的实用性真的很出色。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-12
  • 2018-09-27
  • 2012-05-26
  • 2019-08-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多