21

I have this code

myvector <- c(3.45235, 1.32525, ... , 2.41351)    # some numbers
write(myvector, "C:/mypath/myfile.txt")           # I use "/" instead of "\"

and I get the following error:

Error in file(file, ifelse(append, "a", "w")) : cannot open the connection In addition: warning message: In file(file, ifelse(append, "a", "w")) : cannot open file 'C:/mypath/myfile.txt' : No such file or directory

I read this tutorial, but I can't understant what's wrong with my code. Any idea?

edit:

As @dickoa pointed out, I need an existing path to write a file, so I tried to simplify in the following way:

file.exists("C:/")
write(myvector, "C:/myfile.txt")

Surprisingly :P the path "C:/" exists (the result is TRUE) but I get a similar error:

Error in file(file, ifelse(append, "a", "w")) : cannot open the connection In addition: warning message: In file(file, ifelse(append, "a", "w")) : cannot open file 'C:/mypath/myfile.txt' : Permission denied

4

5 回答 5

23

我知道@dickoa 在评论中回答了这个问题,但为了在这里至少提供一个答案,我想通过 Windows 上的 R 来了解一些简单的问题。

  1. 当您使用 Windows 时,您仍然必须使用正斜杠作为路径。在 R 中,反斜杠保留用于转义值。因此,R 中的路径如下所示: C:/path/to/my/directory
  2. 在较新的 Windows 变体中,C:\ 受到保护,不会被用户帐户写入。如果要写入 C:\,您必须是管理员。您可以通过右键单击 Windows 中的 R 图标并选择“以管理员身份运行”来完成此操作。这也应该在您安装软件包时完成。如果您不以管理员身份运行它,您可能无权在某些 Windows 版本上安装软件包。
  3. 如果您不想以管理员身份运行 R,并且想写入文件,则默认情况下您将拥有该C:/Users/username/目录的权限。

再次感谢@dickoa 他的回答。

祝你好运!

于 2013-06-18T01:23:37.123 回答
1

just adding to answers here.

The reason I was facing this error was, the path I was trying to save in exceded 256 characters, and hence the error.

Problem was sorted once I reduced the path size.

于 2019-02-04T04:49:03.793 回答
1

我只是在这里分享了这个答案,并提供了一些更好的解释,但它的要点是:

尝试在 Excel 中打开文件以查看它是否被其他用户锁定。我收到了相同的错误消息,并且能够确定一位同事在他们的计算机上打开了该文件,这使我无法编辑它。

于 2017-09-07T14:10:56.680 回答
1

有时问题在于文件的命名。例如,当文件名中有“\”时,我遇到过这个问题,因为有一个带有名称的动态列表。你可以通过使用类似这样的东西来传递这样的东西:sometext = gsub("/"," ", sometext)。

于 2018-04-04T09:47:11.943 回答
0

当您打开 myfile.txt 并运行代码时会发生这种情况。尝试关闭机器中的 myfile.txt 并运行命令。它解决了你的问题。

于 2020-09-24T07:17:45.587 回答