Open In App

List all Files with Specific Extension in R

Last Updated : 17 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

R programming language contains a wide variety of method to work with directory and its associated sub-directories. There are various inbuilt methods in R programming language which are used to return the file names with the required extensions. It can be used to efficiently locate the presence of a file. 

Directory in use:

Method 1 : Using list.files() method

The list.files() method in R language is used to produce a character vector of the names of files or directories in the named directory. The regular expression is specified to match the files with the required file extension. The ‘$‘ symbol indicates the end-of-the-string, and the ‘\\‘ symbol before the ‘.’ is used to make sure that the files match the specified extension exactly. The pattern is case-sensitive, and any matches returned are strictly based on the specified characters of the pattern. 

The file names returned are sorted in alphabetical order.

Syntax:

list.files(path = “.”, pattern = NULL, full.names = FALSE, ignore.case = FALSE)

Parameters : 

  • path – (Default : current working directory) A character vector of full path names
  • pattern – regular expression to match the file names with
  • full.names – If TRUE, returns the absolute path of the file locations
  • ignore.case – Indicator of whether to ignore the case while searching for files.

Example:

R




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


Output

[1] “Names of files” 

[1] “cubegfg.pdf”       “maytravelform.pdf”

The case of the file name can also be ignored by setting the attribute of ignore.case as the TRUE. 

Example:

R




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


Output

[1] “Names of files” 

[1] “cubegfg.pdf”       “maytravelform.pdf” “pdf2.pDf”

Method 2 : Using Sys.glob() method

The Sys.glob() method in R is used to extract the file names with the matched pattern. This method is used to expand wild cards, termed as “globbing” in file paths. The special character “*” is used to find matches for zero or more characters, in the retrieved string. 

Syntax:

Sys.glob ( pattern)

Parameters : 

  • pattern – character vector of patterns for relative or absolute file paths

Example:

R




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


Output

[1] “Names of files” 

[1] “Screenshot 2021-06-03 at 4.35.54 PM.png” “cubegfg.png”                            

[3] “gfg.png” 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads