【问题标题】:Reading multiple files from a directory, R从目录中读取多个文件,R
【发布时间】:2014-08-18 12:24:43
【问题描述】:

我在代码中的一步读取文本文件文件夹并将其转换为 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]
}

【问题讨论】:

    标签: r


    【解决方案1】:

    List.files只给你文件名,而不是带有完整路径的文件名。试试

    files <- as.character(list.files(path="[file path]"))
    readLines(paste("[file path]",.Platform$file.sep,files[1],sep=""))
    

    【讨论】:

    • 或者只使用list.filesfull.names = TRUE
    • 哇哦。谢谢。这只是一个工作目录问题。抱歉浪费了时间!
    【解决方案2】:
    directory <- "C://temp"  ## for example
    filenames <- list.files(directory, pattern = "*.*", full.names = TRUE)
    

    【讨论】:

    • 对我很有帮助。非常感谢 +1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 2013-09-04
    相关资源
    最近更新 更多