user2128119
user2128119

Reputation: 115

Looping through folder and finding specific file in R

I am trying to loop through many folders in a directory, looking for a particular xml file buried in one of the folders. I would then like to save the location of that file and then run my code against that file (I will not include that code in this). What I am asking here is to loop through all the folders and then open the specific file. For example: My main folder would be: C:\Parsing It has two folders named "folder1" and "folder2". each folder has an xml file that I am interested in, lets say its called "needed.xml" I would like to have a scrip that loops through the directory and finds those particular scripts. Do you know how I could that in R.

Upvotes: 2

Views: 1862

Answers (3)

Silence Dogood
Silence Dogood

Reputation: 3597

Using list.files and greplyou could look recursively through all sub-folders

rootPath="C:\Parsing"
listFiles=list.files(rootPath,recursive=TRUE)
searchFileName="needed.xml"

presentFile=grepl(searchFileName,listFiles)


if(nchar(presentFile)) cat("File",searchFileName,"is present at", presentFile,"\n")

Upvotes: 3

Komal Rathi
Komal Rathi

Reputation: 4274

I would do something like this (replace *.xml with your filename.xml if you want):

list.files(path = "C:\Parsing", pattern = "*.xml", recursive = TRUE, full.names = TRUE)

This will recursively look for files with extension .xml in the path C:\Parsing and return the full path of the matched files.

Upvotes: 0

Matt
Matt

Reputation: 468

Is this what you're looking for?

require(XML)

fol <- list.files("C:/Parsing")

for (i in fol){
               dir <- paste("C:/Parsing" , i, "/needed.xml",  sep = "")

                 if(file.exists(dir) == T){
                                           needed <- xmlToList(dir) 
                                           }
              }

This will locate your xml file and read it into R as a list. I wasn't clear from your question if you wanted the output to be the data itself or just the directory location of your data which could then be supplied to another function/script. If you just want the location, remove the 'xmlToList' function.

Upvotes: 0

Related Questions