Skip to content

R errors when trying to read a file

2 messages · Dennis Fisher, Brian Ripley

#
Colleagues,

I have encountered a problem in version 2.9 of R, running in both  
Vista and OS X.  My code is quite lengthy but the critical line is:
	if (file.exists(FILENAME))	readLines(FILENAME))

This triggers the error:
	Error in file(con, "r") : cannot open the connection
	Calls: readLines -> file
	Execution halted

The file that it is reading is being created on the fly, then  
eventually deleted.  The conditional was used to ensure that the  
readLines command would be executed only when the file existed.

Is it possible that the file is deleted AFTER the conditional is  
evaluated but before the readLines command is executed?  If so, is  
there any means to prevent an error condition?

Any help will be greatly appreciated.  Thanks.

Dennis

Dennis Fisher MD
P < (The "P Less Than" Company)
Phone: 1-866-PLessThan (1-866-753-7784)
Fax: 1-415-564-2220
www.PLessThan.com
#
On Mon, 11 May 2009, Dennis Fisher wrote:

            
It is possible.  But so are a lot of other things, and your pretest is 
just not enough -- for example another process might have the file 
open for exclusive access (quite common in the Windows world) in which 
case it exists but you cannot open it for reading.

There is only one sure way to find out if you can read a file, and 
that is to try to read it.  So I'd simply use try() or tryCatch() on 
the readLines call.