我的脚本中有一行代码,用于检查文件是否存在(实际上,有许多文件,这一行将循环用于一堆不同的文件):
file.exists(Sys.glob(file.path(getwd(), "files", "*name*")))
它查找目录/ file /中有"name“的任何文件,例如"filename.csv”。但是,我的一些文件名为"fileName.csv“或"thisfileNAME.csv”。他们得不到认可。如何使file.exists以不区分大小写的方式对待此检查?
在我的其他代码中,我通常使用tolower函数立即生成任何导入的名称或列表。但是我没有看到在file.exists函数中包含这个选项。
发布于 2020-02-19 15:06:06
使用list.files
的建议解决方案
如果我们有很多文件,我们可能只想这样做一次,否则我们可以放入函数(并将path_to_root_directory
而不是found_files
传递给函数)
found_files <- list.files(path_to_root_directory, recursive=FALSE)
行为为file.exists
(返回值为布尔值):
fileExIsTs <- function(file_path, found_files) {
return(tolower(file_path) %in% tolower(found_files))
}
如果不匹配,则返回值是具有拼写的文件,如在目录或character(0)
中找到:
fileExIsTs <- function(file_path, found_files) {
return(found_files[tolower(found_files) %in% tolower(file_path)])
}
编辑:
适应新要求的新解决方案:
keywordExists <- function(keyword, found_files) {
return(any(grepl(keyword, found_files, ignore.case=TRUE)))
}
keywordExists("NaMe", found_files=c("filename.csv", "morefilenames.csv"))
返回:
[1] TRUE
或
如果不匹配,则返回值是具有拼写的文件,如在目录或character(0)
中找到:
keywordExists2 <- function(file_path, found_files) {
return(found_files[grepl(keyword, found_files, ignore.case=TRUE)])
}
keywordExists2("NaMe", found_files=c("filename.csv", "morefilenames.csv"))
返回:
[1] "filename.csv" "morefilenames.csv"
发布于 2020-02-19 15:15:18
在任何情况下,如果文件名匹配,则返回1;如果不匹配,则返回0。
max(grepl("*name*",list.files()),ignore.case=T)
https://stackoverflow.com/questions/60302960
复制相似问题