我的代码中有一步难以读取文本文件夹并将其转换为dtm。问题是,由于某种原因,我的计算机只能间歇性地与目录中的文本文件建立连接。返回的错误是:
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
但是,我可以在任何文本编辑器和python中轻松打开这些文件。任何想法为什么我有时可以建立连接而不是其他人?我的代码如下:
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]
}
答案 0 :(得分:9)
List.files
仅为您提供文件名,而不是具有完整路径的文件名。尝试
files <- as.character(list.files(path="[file path]"))
readLines(paste("[file path]",.Platform$file.sep,files[1],sep=""))
答案 1 :(得分:1)
directory <- "C://temp" ## for example
filenames <- list.files(directory, pattern = "*.*", full.names = TRUE)