In this article, we are going to see how to fix the error in file(file, “rt”) : cannot open the connection. When error that one may face in R is:
Error in file(file, "rt") :
cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file 'sample.csv':
No such file or directory
The R compiler produces such an error when one tries to read a CSV file but the file or the directory that is being accessed does not exist.
When this error might occur in R
Let’s consider that we have a CSV file: Sample and we want to read it:
R
df <- read.csv ( 'sample.csv' )
|
Output:

The R compiler produces this error because there is no CSV file by the name sample in the current working directory.
How to Fix the Error
To get the current working directory in which we are in, we can use the getwd() function in R:
Example:
Output:
Method 1: Using setwd()
Since the sample.csv file is located in C:\Users\harsh\Desktop\GeeksforGeeks directory, hence we need to move to this directory. In R, we can move from the current working directory to any other directory using the setwd() function:
R
setwd ( 'C:\\Users\\harsh\\Desktop\\GeeksforGeeks' )
dataframe <- read.csv ( 'sample.csv' , header= TRUE ,
stringsAsFactors= FALSE )
dataframe
|
Output:

Hence, we are able to read the sample.csv file now.
Method 2: Using read.csv()
Another way is to access the csv file by giving the complete path of the file instead of going to that directory:
Example:
R
dataframe <- read.csv ( 'C:\\Users\\harsh\\Desktop\\GeeksforGeeks\\sample.csv' ,
header= TRUE , stringsAsFactors= FALSE )
dataframe
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
29 Mar, 2022
Like Article
Save Article