LISTING ALL THE FILES WITH A SPECIFIED EXTENSION USING R

[This article was first published on R – Greetz to Geeks, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

For listing all the files in your current working directory we can use following function,

 list.files()

list-files

Note: By default, the current working directory will be your home directory. For managing the workspaces (choosing the folder or directory) we can use the setwd() and getwd(). Refer my previous post on Managing workspaces in R

What if we need to list only the files with a specified extension ? In that case, we can make use of the functions Sys.glob() and the list.files() along with some arguments.

If we need to list only the files with the extension (say .csv) from our working directory,

list.files(pattern = “\\.csv$”)

2

Here we use the regular expression to match the files with the specified file extension. The ‘$‘ symbol shows the end-of-the-string, ‘\\‘ symbol is used to make sure that the files match the specified extension exactly.

Note: The above command is case sensitive and only displays the file extensions in lower case. If your file extension contains upper cases or a combination of both upper and lower cases then specify it in the function as shown,

list.files(pattern = “\\.csv$”, ignore.case=TRUE)

3

Note: This command can also work without ‘\\’ symbol. In this case the files which has the string ‘csv’ in its extension will be listed.

list.files(pattern = “.csv$”)

4

The Sys.glob() can also be used for listing the files which has a specified extension

Sys.glob(“*.csv”)
The symbol ‘*’ means zero or more characters

5

Note: This function is also case sensitive. Both the list.files(pattern = “\\.csv$”) and Sys.glob(“*.csv”) gives similar results except that Sys.glob() returns a sorted list of files.


To leave a comment for the author, please follow the link and comment on their blog: R – Greetz to Geeks.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)