How to check if a file exists in Ruby?

This article will discuss how to check if a file exists in Ruby. Checking if a file exists is important whether you are managing file operations, creating applications or handling data. The intention of this guide however is to offer a detailed account of methods that can be used to effectively achieve this objective.

In Ruby, you can check if a file exists using various methods. One common way is to use the File.exist method.

An understanding of file handling concepts and basic knowledge of Ruby programming language are necessary before delving into file existence checking in Ruby. Knowhow about directory structures as well as file paths will also be beneficial.

Some examples of How to check if a file exists in Ruby?

Example #1.

Using File.exist?

Ruby
file_path = "file.txt"
if File.exist?(file_path)
  puts "File exists!"
else
  puts "File does not exist."
end

Checking the existence of a file in a specified directory. This method returns true if the file exists and false otherwise.

Example #2.

Using File.file?:

Ruby
file_path = "file.txt"
if File.file?(file_path)
  puts "File exists!"
else
  puts "File does not exit."
end

Verifying if multiple files exist in a given directory. Specifically checks if the given path points to a regular file or not.

Example #3.

Leveraging exceptions:

Ruby
file_path = "file.txt"
begin
  File.open(file_path)
  puts "File exists!"
rescue Errno::ENOENT
  puts "File does not exist."
end

Handling file existence within a conditional statement. Handling exceptions, such as Errno::ENOENT, to capture file existence scenarios.


Contact Us