【问题标题】:Getting error in file(file, "rt"): cannot open the connection文件中出现错误(文件,“rt”):无法打开连接
【发布时间】:2018-08-11 22:29:40
【问题描述】:

我正在运行以下代码...

#Create a list of all the files
file.list <- list.files(path="~/R/natural-language-processing/class-notes", pattern=".csv")

#Loop over file list importing them and binding them together
D1 <- do.call("rbind",lapply(file.list, read.csv, header = TRUE, stringsAsFactors = FALSE))

这是我在上面运行do.call 行时遇到的错误。

文件中的错误(文件,“rt”):无法打开连接

我已尝试重置我的 wd。我现在的getwd()

~/R/natural-language-processing

我看过另一个

文件错误(文件,“rt”):无法打开连接

【问题讨论】:

  • 路径好像不正确。尝试删除波浪号。
  • 这些更改仍然出现同样的错误。 file.list &lt;- list.files(path="C:/Users/Bob/Documents/R/natural-language-processing/class-notes", pattern=".csv") getwd()"C:/Users/Bob/Documents/R/natural-language-processing"
  • 只是为了检查这个路径是否正确。删除模式并查看是否获得目录中的文件列表。
  • 模式被删除,我仍然在目录中得到相同的文件列表。
  • list.files中使用full.names = TRUE

标签: r read.table read.csv


【解决方案1】:

您很可能尝试从工作目录打开文件,而不是您调用list.files 的目录。而是尝试

D1 <- do.call("rbind",
              lapply(paste0("~/R/natural-language-processing/class-notes/",
                            file.list),
                     read.csv, header = TRUE, stringsAsFactors = FALSE))

或者,您可以在list.files 中将full.names 参数设置为TRUE 以获得完整路径:

file.list <- list.files(path="~/R/natural-language-processing/class-notes", 
                        pattern=".csv", full.names = TRUE)

【讨论】:

  • 另外,作为一个小建议,在使用read.csv 时设置header=TRUE 是不必要的,这是默认设置(与read.table 相比)。
【解决方案2】:

read.csv 正在您的工作目录中查找文件名。通过将您的工作目录更改为“C:/Users/Bob/Documents/R/natural-language-processing/class-notes”,您的代码应该可以正常工作。

代码:

setwd("C:/Users/Bob/Documents/R/natural-language-processing/class-notes")

然后重新运行您的代码。

【讨论】:

  • 请注意,这只有在您使用 Windows 时才有效
  • @an2825 - 运行 getwd() 时的输出是什么?也许尝试通过单击会话 -> 设置工作目录 -> 选择目录然后选择正确的文件夹来手动设置您的工作目录。
【解决方案3】:

我也花了很多时间试图了解我的代码出了什么问题...

如果你使用的是windows,这似乎很简单。

当您将文件命名为“blabla.txt”时,Windows 将其命名为“blabla.txt.txt”...这与 .CSV 文件相同,因此 Windows 会在您调用时创建一个名为“001.csv.csv”的文件它“001.csv”

因此,当您创建 .csv 文件时,只需将其重命名为“001”并在 R 中使用 read.table("/absolute/path/of/directory/with/required/001.csv") 打开它

它对我有用。

【讨论】:

    【解决方案4】:

    在我的情况下,问题在于包含 *.csv 文件的目录内部也是另一个目录。一旦我从文件夹中移动目录,特定错误就消失了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-12
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多