R test if a file exists, and is not a directory

2020-02-12 02:56发布

问题:

I have an R script that takes a file as input, and I want a general way to know whether the input is a file that exists, and is not a directory.

In Python you would do it this way: How do I check whether a file exists using Python?, but I was struggling to find anything similar in R.

What I'd like is something like below, assuming that the file.txt actually exists:

input.good = "~/directory/file.txt"
input.bad = "~/directory/"

is.file(input.good) # should return TRUE
is.file(input.bad) #should return FALSE

R has something called file.exists(), but this doesn't distinguish files from directories.

回答1:

There is a dir.exists function in all recent versions of R.

file.exists(f) && !dir.exists(f)


回答2:

The solution is to use file_test()

This gives shell-style file tests, and can distinguish files from folders.

E.g.

input.good = "~/directory/file.txt"
input.bad = "~/directory/"

file_test("-f", input.good) # returns TRUE
file_test("-f", input.bad) #returns FALSE

From the manual:

Usage

file_test(op, x, y) Arguments

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.



回答3:

You can also use is_file(path) from the fs package.



标签: r file directory