I have an Array of Strings and I want to select only these Strings which are paths to files:
My path is "~/dlds/some_file.ics"
where ~/dlds
is a symlink to ~/archive/downloads
on my system. The file has following permissions:
-rw-r--r--
My code (I tried several variants):
ARGV.select do |string|
File.file? string # returns false
Pathname.new(string).file? # returns false
Pathname.new(string).expand_path.file? # returns false
end
I don't know what else to try.
I'm running Ruby 2.2.0 or 2.2.2.
If you’re not familiar with object-oriented programming, check out the Python OOP section. First, import the Path class from the pathlib module: Then, instantiate a new instance of the Path class and initialize it with the file path that you want to check for existence:
Finally, check if the file exists using the is_file () method: If the file doesn’t exist, the is_file () method returns False. Otherwise, it returns True. The following example shows how to use the Path class from the pathlib module to check if the readme.txt file exists in the same folder of the program:
I would recommend using isFile () instead of exists (). Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists () will return true if your path points to a directory. new File ("C:/").exists () will return true but will not allow you to open and read from it as a file.
os.path.exists ( path_to_file) Code language: CSS (css) If the file exists, the exists () function returns True. Otherwise, it returns False. If the file is in the same folder as the program, the path_to_file is just simply the file name. However, it’s not the case, you need to pass the full file path of the file.
File.exist? File.expand_path "~/dlds/some_file.ics"
Your question is a bit confusing. If you want to check if the file exists, you should just do as you did:
Pathname.new(file_name).file?
If you are using the ~
you will first have to expand the path, so write:
Pathname.new(file_name).expand_path.file?
If you want to check if the given file_name
is a symlink, you can just do
Pathname.new(file_name).expand_path.symlink?
If you want to find the file the symlink points to, you have to follow the link:
File.readlink(Pathname.new(file_name).expand_path)
which will return the filename of the linked file, so if you really wanted you could do something like:
Pathname.new(File.readlink(Pathname.new(file_name).expand_path)).file?
to make sure the symlink is pointing to an existing file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With