【发布时间】:2022-01-23 18:20:09
【问题描述】:
我正在使用 R 编程语言。
我发现了以下相关问题 Stackoverflow (how to delete a file with R?),它向您展示了如何从工作目录中删除具有特定名称的文件:
#Define the file name that will be deleted
fn <- "foo.txt"
#Check its existence
if (file.exists(fn)) {
#Delete file if it exists
file.remove(fn)
}
[1] TRUE
我的问题:是否可以根据文件名是否包含特定的字母组合(即LIKE 'fo%')来删除文件?这样,工作目录中所有以“fo”开头的文件都会被删除。
到目前为止我尝试了什么:
我想到了一种方法,首先我可以根据它们的名称创建工作目录中我想要删除的所有文件的列表:
# create list of all files in working directory
a = getwd()
path.to.csv <- a
files<-list.files(path.to.csv)
my_list = print(files) ## list all files in path
#identify files that match the condition
to_be_deleted = my_list[grepl("fo",unlist(my_list))]
然后,我尝试使用之前使用的命令删除此文件:
if (file.exists(to_be_deleted)) {
#Delete file if it exists
file.remove(to_be_deleted)
}
这返回了以下消息:
[1] TRUE TRUE TRUE TRUE TRUE TRUE
Warning message:
In if (file.exists(to_be_deleted)) { :
the condition has length > 1 and only the first element will be used
有人知道我这样做是否正确吗?假设如果工作目录中有多个文件,这些文件的名称以“fo”开头 - 所有这些文件是否都已被删除?还是仅此列表中的第一个文件?
有人可以告诉我如何正确执行此操作吗?
谢谢!
【问题讨论】:
标签: r delete-file