Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

statistics

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!

like image 751
user2051347 Avatar asked Jan 05 '14 13:01

user2051347


People also ask

How do I check to see if a file exists?

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 .

Which of the following can be used to check whether a file exists or not in Python?

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.


2 Answers

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) 
like image 147
Mark Heckmann Avatar answered Oct 01 '22 04:10

Mark Heckmann


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')) 
like image 42
Rupesh Kumar Avatar answered Oct 01 '22 05:10

Rupesh Kumar