3

I am having difficulty with one step in my code to read in a folder of text files and convert it to a dtm. The problem is that, for some reason, my computer is only able to intermittently establish a connection with the text files in the directory. The error that returns is:

Error in file(con, "r") : cannot open the connection
In addition: Warning message:
In file(con, "r") :
  cannot open file '[file name]': No such file or directory

However, I can easily open these files in any text editor, as well as in python. Any ideas why I might be able to establish the connection sometimes and not others? My code is below:

files <- as.character(list.files(path="[file path]"))
readLines(files[1])  #here is where the error occurs, for example
n <- length(files) #this is my loop
subtitles <- character(n)
subtitle <- character(1)

for (i in 1:n){
   subtitle <- as.character(readLines(files[i]))
   subtitle <- iconv(subtitle, to="UTF8")
   subtitle <-  tolower(subtitle)
   subtitle <- as.character(paste(subtitle, collapse=" "))
   subtitles[i] <- subtitle[1]
}
mjv
  • 73,152
  • 14
  • 113
  • 156
brianabelson
  • 131
  • 1
  • 2
  • 6

2 Answers2

9

List.filesonly gives you the file names, not file names with full path. Try

files <- as.character(list.files(path="[file path]"))
readLines(paste("[file path]",.Platform$file.sep,files[1],sep=""))
morispaa
  • 311
  • 2
  • 5
1
directory <- "C://temp"  ## for example
filenames <- list.files(directory, pattern = "*.*", full.names = TRUE)
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541