LISTING ALL THE FILES WITH A SPECIFIED EXTENSION USING R

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.

Advertisements

2 thoughts on “LISTING ALL THE FILES WITH A SPECIFIED EXTENSION USING R

  1. Dalton Fitzsimmons says:

    This stuff is very satisfactorily written. The blog post was informative to readers who exactly possess a good worth for articles. We looking forward for even more of the very same. He has outlined each and every little thing extremely well and in brief.

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s