R测试文件是否存在,是否不是目录 [英] R test if a file exists, and is not a directory

查看:1325
本文介绍了R测试文件是否存在,是否不是目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个R脚本,它将文件作为输入,并且我想以一种通用的方式来知道输入是否是存在的文件,而不是目录。

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.

在Python中,您可以这样做:如何使用Python检查文件是否存在?,但是我一直在努力寻找R中的类似内容。

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.

我想要的是下面的内容,假设 file.txt 实际上存在:

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有一个叫做file.exists()的东西,但这不能区分文件与目录。

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

推荐答案

使用 file_test()

这提供了外壳样式的文件测试,并且可以区分文件夹中的文件。

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

例如

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

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

从手册中:


用法

file_test(op,x,y)参数

file_test(op, x, y) Arguments

op >指定要执行的测试的字符串。一元
测试(仅使用x)是 -f(存在而不是目录),
-d(存在和目录)和 -x(可作为文件执行或
可作为目录搜索)。二进制测试分别是 -nt(使用修改日期比
严格更新)和 -ot(必须比使用日期更早):
在两种情况下,除非两个文件都存在,否则测试均为假。

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 字符向量提供文件路径。

x, y character vectors giving file paths.

这篇关于R测试文件是否存在,是否不是目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆