This question already has an answer here:
这个问题已经有了答案:
- How to check if a directory/file/symlink exists with one command in Ruby 2 answers
- 如何检查目录/文件/符号链接是否存在Ruby 2中的一个命令
Is there a Ruby class/method where I could pass "a full path", home/me/a_file.txt
, to identify whether it is a valid file path?
是否有一个Ruby类/方法可以通过“完整路径”,home/me/a_file。txt,识别它是否是一个有效的文件路径?
3 个解决方案
#1
44
Check out Pathname and in particular Pathname#exist?
.
检查路径名,特别是路径名#exist?。
File and its FileTest module are perhaps simpler/more direct, but I find Pathname
a nicer interface in general.
File和它的FileTest模块可能更简单/更直接,但是我发现Pathname通常是更好的接口。
#2
460
# file? will only return true for files
File.file?(filename)
and
和
# Will also return true for directories - watch out!
File.exist?(filename)
#3
13
NOTE: file?
will only return true for files.
注意:文件?将只对文件返回true。
To check if a file exists:
检查文件是否存在:
File.exist?('file_name.csv')
O/P: true
You can also use it for directories:
你也可以把它用于目录:
File.exist?('~/dir_name')
O/P: true
#1
44
Check out Pathname and in particular Pathname#exist?
.
检查路径名,特别是路径名#exist?。
File and its FileTest module are perhaps simpler/more direct, but I find Pathname
a nicer interface in general.
File和它的FileTest模块可能更简单/更直接,但是我发现Pathname通常是更好的接口。
#2
460
# file? will only return true for files
File.file?(filename)
and
和
# Will also return true for directories - watch out!
File.exist?(filename)
#3
13
NOTE: file?
will only return true for files.
注意:文件?将只对文件返回true。
To check if a file exists:
检查文件是否存在:
File.exist?('file_name.csv')
O/P: true
You can also use it for directories:
你也可以把它用于目录:
File.exist?('~/dir_name')
O/P: true