如何检查文件是否存在[副本]

时间:2021-09-10 09:15:11

This question already has an answer here:

这个问题已经有了答案:

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