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


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 read in a CSV file in R, 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:\Users\Bob\Desktop\data.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

It worked!

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

Additional Resources

How to Import CSV Files into R
How to Import Excel Files into R
How to Manually Enter Raw Data in R

Leave a Reply

Your email address will not be published.