December 15, 2016

(This article was first published on R – Greetz to Geeks, and kindly contributed to R-bloggers)

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



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$”)


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$”,


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$”)


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

The symbol ‘*’ means zero or more characters


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. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


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)