📌  相关文章
📜  列出 R 中具有特定扩展名的所有文件

📅  最后修改于: 2022-05-13 01:54:18.820000             🧑  作者: Mango

列出 R 中具有特定扩展名的所有文件

R 编程语言包含多种处理目录及其相关子目录的方法。 R 编程语言中有各种内置方法,用于返回具有所需扩展名的文件名。它可用于有效定位文件的存在。

使用目录:

方法 1:使用 list.files() 方法

R 语言中的 list.files() 方法用于生成命名目录中文件或目录名称的字符向量。指定正则表达式以匹配具有所需文件扩展名的文件。 '$' 符号表示字符串的结尾,'.' 之前的 '\\' 符号。用于确保文件与指定的扩展名完全匹配。模式区分大小写,返回的任何匹配都严格基于模式的指定字符。

返回的文件名按字母顺序排序。



例子:

R
# list all the file names of the
# specified pattern
fnames <- list.files(pattern = "\\.pdf$")
  
print ("Names of files")
print (fnames)


R
# list all the file names of the 
# specified pattern
fnames <- list.files(pattern = "\\.pdf$", 
                     ignore.case = TRUE)
  
print ("Names of files")
print (fnames)


R
# list all the file names of 
# the specified pattern
fnames <- Sys.glob("*.png")
  
print ("Names of files")
print (fnames)


输出

通过将 ignore.case 的属性设置为 TRUE,也可以忽略文件名的大小写。

例子:

电阻

# list all the file names of the 
# specified pattern
fnames <- list.files(pattern = "\\.pdf$", 
                     ignore.case = TRUE)
  
print ("Names of files")
print (fnames)

输出

方法 2:使用 Sys.glob() 方法

R 中的 Sys.glob() 方法用于提取具有匹配模式的文件名。此方法用于扩展通配符,在文件路径中称为“通配符”。特殊字符“*”用于在检索到的字符串查找零个或多个字符的匹配项。

例子:

电阻

# list all the file names of 
# the specified pattern
fnames <- Sys.glob("*.png")
  
print ("Names of files")
print (fnames)

输出