Reading multiple files from a directory, R

I am having difficulty with one step in my code to read text files in a folder and convert it to dtm. The problem is that for some reason, my computer can only periodically establish a connection with text files in a directory. Return Error:

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 could make a 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]
}
+3
source share
2 answers

List.filesgives you file names, not file names with a full path. Try

files <- as.character(list.files(path="[file path]"))
readLines(paste("[file path]",.Platform$file.sep,files[1],sep=""))
+9
source
directory <- "C://temp"  ## for example
filenames <- list.files(directory, pattern = "*.*", full.names = TRUE)
+1
source

All Articles