Cannot export data to a file in R (write.csv) - r

I am trying to export data in R to a csv file, and as much simple as I try to do it, I always get the same error message. Example:
I create a simple data vector to export
x <- c(1,3,4,3,5,7,5,8,2,5,7)
I try to export with:
write.csv(x,file='whatever.csv')
And I get an 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 'whatever.csv': Permission denied
How can I solve this?

First part is to check the working directory and ensure that you have write access to that directory. You can check this with getwd(). I can reproduce your error by trying to write to a directory which is read only.
To set the working directory to something else with read access you can type setwd("H:/foo").
Once you have write access the write.csv(x,file='whatever.csv') should work.

I got the same issue today and I know I have full permission to the folder. What worked for me is giving it the absolute path.
write.csv(data, file="C:/project/file.csv")

If you don't specify a filename (i.e. C:/temp.csv) and just provide a file path, this same error pops up with both write.csv and write_csv.

I got this error today and fixed it by granting everyone write permission to the folder.
Steps: locate the folder on your PC, right-click and select properties, look for the "Security" tab and edit the permission for all to include "Write"

I got this error today because the file I try to rewrite on was open in another program. After I closed it, the problem solved.

Related: I was trying to save a csv to a relative path, that I built incrementally in Windows, but in my case the problem wasn't an error really, but a misunderstanding on my part - in the following code:
library(dplyr)
library(hflights)
path_to_hflights_as_csv <-
file.path(path.expand("~/MyHomeSubDir"),
"hflights.csv")
write.csv(hflights, path_to_hflights_as_csv)
path.expand("~/MyHomeSubDir") is mapped to "C:/Users/my.username/Documents/MyHomeSubDir" instead of "C:/Users/my.username/MyHomeSubDir".
Searching if it was some faulty config while installing R, I found that "home dir" in various Windows versions is indeed "C:/Users/my.username/Documents/" (and not "C:/Users/my.username"):
https://en.wikipedia.org/wiki/Home_directory
https://cran.r-project.org/bin/windows/base/rw-FAQ.html#What-are-HOME-and-working-directories_003f
And when you pass a path including a sub directory that doesn't exist to utils::csv.write the error is similar (only the reason to not opening file is different - cannot open file 'C:/Users/my.username/MyHomeSubDir/hflights.csv': No such file or directory).

I just stumbled across this question in trying to figure it out myself. I had the exact same error message pop up a few times:
Error in file(file, ifelse(append, "a", "w")) :
cannot open the connection
After searching around and finding nothing that worked for me I restarted R and received the same message, but also a new error:
In addition: Warning message:
In file(file, ifelse(append, "a", "w")) :
cannot open file 'censoredpath.file.csv': Permission denied
I went to my file explorer and attempted to open the .csv in Excel and it notified me that it was locked by another user (someone else had the file open on their computer). So if it's not a problem with having access to the directory like what's already been suggested, try opening it in Excel to see if that might be the problem.

In case you tried everything and did not work, check your antivirus. In my case AVAST was causing this issue for some reason.

Related

R unable to write CSVs post update [duplicate]

I am trying to export data in R to a csv file, and as much simple as I try to do it, I always get the same error message. Example:
I create a simple data vector to export
x <- c(1,3,4,3,5,7,5,8,2,5,7)
I try to export with:
write.csv(x,file='whatever.csv')
And I get an 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 'whatever.csv': Permission denied
How can I solve this?
First part is to check the working directory and ensure that you have write access to that directory. You can check this with getwd(). I can reproduce your error by trying to write to a directory which is read only.
To set the working directory to something else with read access you can type setwd("H:/foo").
Once you have write access the write.csv(x,file='whatever.csv') should work.
I got the same issue today and I know I have full permission to the folder. What worked for me is giving it the absolute path.
write.csv(data, file="C:/project/file.csv")
If you don't specify a filename (i.e. C:/temp.csv) and just provide a file path, this same error pops up with both write.csv and write_csv.
I got this error today and fixed it by granting everyone write permission to the folder.
Steps: locate the folder on your PC, right-click and select properties, look for the "Security" tab and edit the permission for all to include "Write"
I got this error today because the file I try to rewrite on was open in another program. After I closed it, the problem solved.
Related: I was trying to save a csv to a relative path, that I built incrementally in Windows, but in my case the problem wasn't an error really, but a misunderstanding on my part - in the following code:
library(dplyr)
library(hflights)
path_to_hflights_as_csv <-
file.path(path.expand("~/MyHomeSubDir"),
"hflights.csv")
write.csv(hflights, path_to_hflights_as_csv)
path.expand("~/MyHomeSubDir") is mapped to "C:/Users/my.username/Documents/MyHomeSubDir" instead of "C:/Users/my.username/MyHomeSubDir".
Searching if it was some faulty config while installing R, I found that "home dir" in various Windows versions is indeed "C:/Users/my.username/Documents/" (and not "C:/Users/my.username"):
https://en.wikipedia.org/wiki/Home_directory
https://cran.r-project.org/bin/windows/base/rw-FAQ.html#What-are-HOME-and-working-directories_003f
And when you pass a path including a sub directory that doesn't exist to utils::csv.write the error is similar (only the reason to not opening file is different - cannot open file 'C:/Users/my.username/MyHomeSubDir/hflights.csv': No such file or directory).
I just stumbled across this question in trying to figure it out myself. I had the exact same error message pop up a few times:
Error in file(file, ifelse(append, "a", "w")) :
cannot open the connection
After searching around and finding nothing that worked for me I restarted R and received the same message, but also a new error:
In addition: Warning message:
In file(file, ifelse(append, "a", "w")) :
cannot open file 'censoredpath.file.csv': Permission denied
I went to my file explorer and attempted to open the .csv in Excel and it notified me that it was locked by another user (someone else had the file open on their computer). So if it's not a problem with having access to the directory like what's already been suggested, try opening it in Excel to see if that might be the problem.
In case you tried everything and did not work, check your antivirus. In my case AVAST was causing this issue for some reason.

Read() function in R is looking at wrong folder

When I'm calling any read.___() function in R it is looking at the wrong file path. I have tried changing the working directory multiple times and it keeps going to the same path. For example I'm trying the following:
setwd("C:/OneDrive/")
read.csv("~/Desktop/Data/file.csv")
I then get the following error:
Error in file(file, "rt") : cannot open the connection In addition:
Warning message: In file(file, "rt") : cannot open file
'C:/OneDrive/Documents/Desktop/Data/file.csv': No such file
or directory
For some reason the read() function adds the documents folder in place of the specified working directory. I tried uninstalling and deleting all files related to R on my computer then reinstalling. I still get the same issue. I've seen others ask a similar question, but everyone keeps telling them to set the working directory to something different. It doesn't matter what I set the working directory to. R keeps adding the Documents folder into the path. How do I get it to stop adding the Documents folder?

Why I get this error writing data to a file

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
I know #dickoa answered the question in the comments, but in order to provide at least one answer here, I wanted to go through a few simple gotchas with R on Windows.
When you are using Windows, you still have to use forward slashes for paths. In R, backslashes are reserved for escaping values. So a path in R looks like:
C:/path/to/my/directory
In newer variants of Windows, the C:\ is protected from writes by user accounts. If you want to write to the C:\, you must be an administrator. You can accomplish this by right-clicking on the R icon in Windows and choosing "Run as an administrator." This should also be done when you're installing packages. You may not have rights to install packages on certain Windows versions if you don't run it as an administrator.
If you don't want to run R as an administrator, and you want to write to files, you will by default have rights to the C:/Users/username/ directory.
All credit to #dickoa again for his answer in first.
Best of luck!
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.
I just shared this answer with a bit of a better explanation here, but the gist of it is:
Try opening the file in Excel to see if it's locked by another user. I was receiving the same error messages and was able to figure out that a colleague had the file open on their computer which had locked me out of the ability to edit it.
Sometimes the problem is in the naming of the file. For example,I have encountered this issue when in the name of the file there was as "\", as there was a dynamic list with names. You can pass by such thing by using something like: sometext = gsub("/"," ", sometext).
It happens when you open the myfile.txt and run the code. Try to close the myfile.txt in your machine and run the command. It solves your problem.
Just another possibility. I have encountered this problem when running the following code. Because I have successfully run this code before this starting RStudio, I run successfully after restarting RStudio this time. So, sometimes, restarting will solve the problem, although I haven't figured out what happened behind.
DT::datatable(
dt.cmbn,
extensions = c('ColReorder','FixedColumns'), rownames = FALSE,
options = list(
colReorder = TRUE,
#dom = 'Bfrtip',
#buttons = I('colvis'),
scrollX = TRUE,
fixedColumns = TRUE
)
)

Error in gzfile(file, "wb"): cannot open the connection or compressed file

I'm trying to run two things: first, I'm creating a PDF with 4x5, ending with dev.off(), and then trying to create a new graph. However, after starting the second plot, I get:
Error in gzfile(file, "wb") : cannot open the connection
In addition: Warning message:
In gzfile(file, "wb") :
cannot open compressed file '/var/folders/n9/pw_dz8d13j3gb2xgqb6rfnz00000gn/T/RtmpTfm1Ur/rs-graphics-822a1c83-b3fd-46c3-8028-4e0778f91d0c/4db4b438-ac35-403b-b791-e781baba152c.snapshot', probable reason 'No such file or directory'
Graphics error: Error in gzfile(file, "wb") : cannot open the connection
What is this error? The working directory is one I have read/write access to, and my hard drive isn't full.
Also, I'm using RStudio.
This is a bit late but for anyone coming here for help, I got this error when I was trying to write a file from RStudio and my destination file path was very long. I realized this could be a problem because when I wrote the file to another location with a shorter name and tried to copy it into my original destination, Windows gave me an error saying "File path too long". You might need to save the original file into another location with a shorter absolute path.
Maybe you should look here. At the end it says
Note:
The most common reason for failure is lack of write permission in the current directory. For save.image and for saving at the end of a session this will shown by messages like
Error in gzfile(file, "wb") : unable to open connection
In addition: Warning message:
In gzfile(file, "wb") :
cannot open compressed file '.RDataTmp',
probable reason 'Permission denied'
So rapidly, if you try getwd(), look at where is your working directory set. If you're trying to save your document in a place where it's not in your current working directory, it will throw you this error.
At the end of your error message, it says probable reason 'No such file or directory'
Graphics error: Error in gzfile(file, "wb") : cannot open the connection
My diagnosis would be simply that it's trying to save your item in the wrong place and RStudio is not able to find the right place.
This burned me so hopefully saves someone else some toil. The issue was that the classifiers loaded just fine on OS X but on the Linux deployment system they would fail with the error listed in the question. The issue was the the files on the disk had extension abc.RData but the code modelAbc <- readRDS(file="abc.Rdata"). The difference in the upper and lowercase D in the .RData vs .Rdata extension would fail on Linux. It was not very noticeable but check your extensions for case.
You may have no permission to save file in the directory.
On RStudio, get your working directory by getwd().
Then, go to the directory in linux and observe its owner by ls -l.
Now you can change the owner of the directory by chown -R username directoryname.
But you must be root.
Problem resolved by specifying full file path:
saveRDS(df,'C:\\users\\matt\\desktop\\code\\df.Rdata')
I faced this issue lately. Try turning off your anti-virus and build the package, it might help. It worked for me. Usually anti-virus blocks the permissions and you could avoid it by disabling for sometime just before building a package.
I was trying to save an RDS file to my local Dropbox folder so it syncs with my Dropbox.
I figured out I got the same error because I was trying to create a new folder and looks like saveRDS cannot create a new folder, but it can add files to existing folders. So I changed the path to add the file into an existing folder and it worked!
In my case it was Windows Defender which was preventing Rstudio to write any file on hard drive. Either you need to turn Controlled Folder Access off or add Rstudio in the exclusion list.
I also had this problem when working with RStudio and R Markdown. I was getting this error message and had an annoying number of fatal errors which closed RStudio. My issue was that I was working off a network drive and either the name was too long, as in #AHedge above or my network firewalls were giving me trouble. For the moment, I have moved my working files to my desktop and things seem to be working fine. Not sure what this means for my file management over time.
Just want to add more clarity(scenarios in my experience) to what M Beausoleil mentioned.
When you are using a shared-working-directory and trying to rewrite the RDS files which are already existing in a working-directory written by some other user, you get this error.
As some people have already quoted that deleting the existing RDS files or changing the working directory works. It's not a magic. It just works because you are writing a new RDS file and not trying to re-write the old ones.
I came into the same problem after I re-install a new version of RStudio.
The Rmarkdown file I created using old version of RStudio shows the same problem.
When I use ggplot() to draw a picture the error code are as follow:
Warning in gzfile(file, "wb") :
cannot open compressed file 'I:/Rlearning/.Rproj.user/shared/notebooks/58A1385C-PCA作图/1/2C15461A183AC56C/cco192gb0pow1_t\_rs_rdf_32004888ecb.rdf', probable reason 'No such file or directory'
Error in gzfile(file, "wb") : cannot open the connection
Solution:
Create a new Rmarkdown file
Delete all codes
Copy your old Rmarkdown code into it.
I had the same problem.For me, it was caused due to not having enough disk space on the drive where R studio was installed.Freeing up space works.
The reason for the error is that your username is Chinese.Please create new user folder with English in the user directory.For example, you could name the folder for "DavidSmith".Then, you need create three folders("AppData","Local","Temp").File directory C:\Users\DavidSmith\AppData\Local\Temp.
In the Advanced system settings which will modify the environment variables TMP and TEMP C:\Users\DavidSmith\AppData\Local\Temp.Save them.
After modification, open RStudio and try again.
Notice:TMP and TEMP are modified in the USER VARIABLE.
I just ran into this problem after changing my system locale.
Check your locale using Sys.getlocale().
Change it to appropriate one using Sys.setLocale("LC_ALL","ENG") (replace "ENG" with appropriate one)
I can't say with certainty which locale would be appropriate, but it seems to be coherent with default OS one.
Hope this helps!
I had this error because of an invalid character in the filename to be used to save the file, in my case "/" (there are many such characters that cannot be used in a filename). I removed the character and it was solved.
In my case, I received the error "Error in gzfile(file, "wb") : cannot open the connection" when trying to exit R in the Anaconda Prompt and saving workspace image. I am using Windows 10 and R-3.5.2. To fix it, I had to go to the Program Files folder, right click and the R folder, then selected Properties. Selected the Security tab, then, in the Group or user names box, selected Users, then clicked Edit. In the Permissions for Users, I checked Full control and Modify and saved the changes. Then I was able to save the workspace image.
I have another instance of this error which seems to be new (or at least not listed here or here: apparently it's not OK to save a file with the name aux.RData. I guess it's a reserved filename.
x <- rnorm(9000)
save(x, file = "aux.RData")
Error in gzfile(file, "wb") : no se puede abrir la conexión
Also: Warning message:
In gzfile(file, "wb") :
cannot open compressed file 'aux.RData', probable reason 'No such file or directory'
But when I change the filename saves with no problem:
save(x, file = "aux_file.RData")
Haven't seen this case in the other answers:
if this seems to happen all the time, and to be very persistent when it does happen, check the default directory in your file handling software connection.
In my case FileZilla was logging on to my DigitalOcean droplet as "root" and whenever I used FileZilla to create a directory it was setting write permissions to "root", whereas my RStudio on the same droplet read/wrote as "My_Name". Anytime I set something up in FZ (e.g. large imported files, renamed or copied) the permissions would switch and I'd get this error.
If this is what is causing frequent error messages it can be solved instantly with chown -R My_Name directoryname but in the longer run, if you are going to be using your file handler to define and create a lot of directories, it will pay to create a connection whose default name is the same name you use for RStudio.
In my case, when it happened first, months ago, the solution here worked.
But recently, it came back, constantly... What solved this time was to change the anti-virus. I have not just the Windows defender, but also a 2nd anti-virus, the same in both times. I ended up deinstalling it and installing another antivirus... After this, the problem did not happen again...
After several days trying to solve this same ERROR or problem in my case (Windows 10 and R), I tried to save my file(file.RData) in D disk instead of C disk (where I always was working and I have installed R) and it was fine, without problems,my file was saved in D:/Users.When I tried many times to save it in C disk, always gave me Permission denied.
save(Myfile, file="D:/Users/Myfile.RData")
I encountered this same issue when trying to save an Rds file from an Markdown file. Changing my relative file path to an absolute file path worked for me.
In my case, this error was because the file that I wanted to re-write, was read-only (for whatever reason, I didn't do it myself). I just right-click on the file's name in the folder and unchecked the read-only property. After that it worked.

How to import files into R?

I'm a new user to R, sorry if my question is too basic.
I've installed the newest version of R on windows 7 and as a practice, i tried to open a .txt file using
students<-read.table("students.txt",header=T,sep="\t")
but there's always an error message as follows:
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file 'students.txt': No such file or directory
I've already changed the directory to where the students.txt resides; but it just doesn't work. Please help!
Thank you very much in advance if anyone can help me solve the problem.
There is an entire R manual devoted to data import / export questions.
Now, if you fail to specify file name and path correctly, use the file.choose() function instead which allows you to point, click and shoot:
students<-read.table(file.choose(),header=T,sep="\t")
The error message is saying that it cannot find the students.txt file. You should try two things:
Call getwd() and confirm that the file is in the directory that is returned.
Try specifying the full path to the file in your read.table() call.
Look at help("read.table") for more detail on the function. You may, for instance, want to change the default to stringsAsFactors=FALSE, depending on your application.
If you use RStudio, which I thoroughly recommend, then you can create a Project with it's own directory. read.csv and friends will then read from that directory by default, which makes it all nice and easy.
This works with R:
first copy the table; then open up R and type:
c <- read.table("clipboard")
then press Enter.

Resources