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

前端 未结 3 905
[愿得一人]
[愿得一人] 2021-01-07 22:21

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

相关标签:
3条回答
  • 2021-01-07 22:59

    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.

    0 讨论(0)
  • 2021-01-07 23:10

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

    file.exists(f) && !dir.exists(f)
    
    0 讨论(0)
  • 2021-01-07 23:11

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

    0 讨论(0)
提交回复
热议问题