Open In App

How to check if a file already exists in R ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to check if a file already exists or not using R Programming Language.

Directory in use:

Check the names of every file in the working directory

First, we will check how many files are available in our directory so for that, we will use list.files() function so it will check how many files are present in our current directory.

R




list.files()


Output:

  [1] "benchmark.png"       "dashboard.pbix"      "data.csv"           
[4] "data.xlsx" "desktop.ini"

Now we will check whether the particular file is existing or not in our directory. for that, we have several methods.

Method 1: Using File.exists()

The function file.exists() returns a logical vector indicating whether the file mentioned in the function existing or not. 

Note: Make sure to provide a file path for those, not in the current working directory.

Syntax: File.exists(“file_path”)

Return value: The function file.exists() returns a logical vector indicating whether the files named by its argument exist.

  • TRUE- file exists
  • FALSE- file does not  exists

Example:

R




file.exists("Akshit.R")


Output:

[1] TRUE

Example 2:

R




file.exists("GFG.R")


Output:

[1] FALSE

Method 2: Using file_test() 

This function can also be used to check whether the file is existing or not.

Syntax: file_test(op, x, y)

Parameter:

  • op: a character string specifying the test to be performed. Unary tests (only x is used) are “-f” (existence and not being a directory), “-d” (existence and directory) and “-x” (executable as a file or searchable as a directory). Binary tests are “-nt” (strictly newer than, using the modification dates) and “-ot” (strictly older than): in both cases the test is false unless both files exist.
  • x, y: character vectors giving file paths.

Returns: The function file_test() returns a logical vector indicating whether the files named by its argument exist.

  • TRUE- file exists
  • FALSE- file does not  exists

Example

R




#"-f" (existence and not
# being a directory)
file_test("-f","Akshit.R")


Output

[1] TRUE

Example 2:

R




file_test("-f","GFG.R")


Output

[1] TRUE

Method 3: if else statement to import a file only if it exists or not

R




# Set the file path
file_path <- "path/to/your/file.txt"
 
# Check if the file exists
 if (file.exists(file_path)) {
  # File exists, proceed with importing it
  data <- read.table(file_path, header = TRUE)
  # Your import or processing logic here
} else {
   # File doesn't exist, handle the situation accordingly
  print(paste("File does not exist:", file_path))
}


Output:

[1] "File does not exist: 'File_name'             


Last Updated : 21 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads