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

喜夏-厌秋 提交于 2019-12-18 05:48:09

问题


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.



来源:https://stackoverflow.com/questions/46147901/r-test-if-a-file-exists-and-is-not-a-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!