33

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!

zx8754
  • 52,746
  • 12
  • 114
  • 209
user2051347
  • 1,609
  • 4
  • 23
  • 34

2 Answers2

52

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)
Mark Heckmann
  • 10,943
  • 4
  • 56
  • 88
  • 2
    Thx for your answer! btw which path is it checking because I am always going into the `else` clause. btw I am running on windows 7. – user2051347 Jan 05 '14 at 14:02
-1

This code can be used to check if a file exits in a folder with date format as TRUE or FALSE.

setwd("D:\\FILEFOLDER")

datafile<-file.exists(paste0('DATA_',format(Sys.Date()-1,'%Y%m%d'),'.gz'))

voicefile<-file.exists(paste0('VOICE_TEXT_',format(Sys.Date()-1,'%Y%m%d'),'.gz'))
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Rupesh Kumar
  • 157
  • 3