user2051347
user2051347

Reputation: 1669

If file exists in folder read it else skip the processing part

I am reading in several *.csv, where the names and paths are determined at runtime.

However sometimes there are files with do not exist. For this file I need kind of exception handling.

Currently I am reading in my files with:

    companyFileName <- paste("C://Users//Prices//",companiesIsin,".csv")
df <- read.csv(gsub(" ","", companyFileName, fixed=TRUE), header = TRUE, sep = ";",stringsAsFactors=FALSE)

When the file does not exist in the folder I am getting an error. Is there something like exception handling in R?

I appreciate your reply!

Upvotes: 39

Views: 53632

Answers (1)

Mark Heckmann
Mark Heckmann

Reputation: 11431

You can check if a file exists using the function file.exists. So you might check for file existence before trying to read it in to avoid an error, e.g.

if (file.exists(companyFileName))
   df <- read.csv(gsub(" ","", companyFileName, fixed=TRUE), header = TRUE, sep = ";",stringsAsFactors=FALSE)

EDIT: You may also simplify the creation of the path and use read.csv2 for the ; separator. This makes it a bit more readable.

f <- paste0("C://Users//Prices//",companiesIsin,".csv")
if (file.exists(f))
  df <- read.csv2(f, TRUE, stringsAsFactors=FALSE)

Upvotes: 57

Related Questions