How to fix: error in file(file, “rt”) : cannot open the connection

This error indicates that the program is not able to open the specified file for reading. To fix this error, make sure that the file path and name are correct, and that the file has the correct permissions to be opened for reading. If the issue persists, try opening the file manually to make sure it is not corrupted or damaged. If this is the case, try to restore the file from a backup.


One common error you may encounter in R is:

Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'data.csv': No such file or directory 

This error occurs when you attempt to , but the file name or directory you’re attempting to access does not exist.

This tutorial shares exactly how to fix this error.

How to Reproduce the Error

Suppose I have a CSV file called data.csv saved in the following location:

C:UsersBobDesktopdata.csv

And suppose the CSV file contains the following data:

team, points, assists
'A', 78, 12
'B', 85, 20
'C', 93, 23
'D', 90, 8
'E', 91, 14

Suppose I use the following syntax to read in this CSV file into R:

#attempt to read in CSV file
df <- read.csv('data.csv')

Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'data2.csv': No such file or directory

I receive an error because this file doesn’t exist in the current working directory.

How to Fix the Error

I can use the getwd() function to actually find the working directory I’m in:

#display current directory
getwd()

[1] "C:/Users/Bob/Documents"

Since my CSV file is located on my desktop, I need to change the working directory using setwd() and then use read.csv() to read in the file:

#set current directory
setwd('C:\Users\Bob\Desktop')

#read in CSV file
df <- read.csv('data.csv', header=TRUE, stringsAsFactors=FALSE)

#view data
df

  team points assists
1    A     78      12
2    B     85      20
3    C     93      23
4    D     90       8
5    E     91      14

Another way to import the CSV without setting the working directory would be to specify the entire file path in R when importing:

#read in CSV file using entire file path
df <- read.csv('C:\Users\Bob\Desktop\data.csv', header=TRUE, stringsAsFactors=FALSE)

#view data
df

  team points assists
1    A     78      12
2    B     85      20
3    C     93      23
4    D     90       8
5    E     91      14

How to Manually Enter Raw Data in R

x