Quantcast
Channel: Greetz to Geeks
Viewing all articles
Browse latest Browse all 10

LISTING ALL THE FILES WITH A SPECIFIED EXTENSION USING R

$
0
0

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.


Viewing all articles
Browse latest Browse all 10

Trending Articles