How to check if a file already exists in R ?
In this article, we will discuss how to check if a file already exists or not using R Programming Languague.
Directory in use:
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 that 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
Please Login to comment...