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!
To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .
isfile() Method to check if file exists. os. path. isfile() method in Python is used to check whether the specified path is an existing regular file or not.
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)
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With