Search code examples
rexcelxlsx

How to remove a 'permission denied' file from folder within R


I am downloading a large xlsx file as a part of a function. This file is removed with file.remove() in linux and mac but I have permission denied in windows machines. Below is the code for my function.

download.file(
'http://mirtarbase.mbc.nctu.edu.tw/cache/download/7.0/miRTarBase_MTI.xlsx',
'miRTarBase.xlsx', mode = "wb")
readxl::read_excel('miRTarBase.xlsx') -> miRTarBase
write.csv(miRTarBase, 'miRTarBase.csv')
read.csv('miRTarBase.csv', row.names = 1) -> miRTarBase
file.remove("miRTarBase.xlsx")

I get the following error message in my console

Warning message:
In file.remove("miRTarBase.xlsx") :
 cannot remove file 'miRTarBase.xlsx', reason 'Permission denied'.

Again this warning only appears in windows.

Furthermore, after checking the properties of the file itself the 'Read-only' attribute is unchecked.

Following this, the following code works perfectly fine so I do not think the issue is with the folder either.

file.remove("miRTarBase.csv")

I believe the issue lies in how .xlsx files are treated in windows.

When I try to delete the .xlsx file while Rstudio is still running I get a File in use warning message. After closing the R session the .xlsx file can be deleted with no hassle.

This has confused me because I am not used to working with windows. Has anyone had this issue before? Would appreciate any help that can be given. Many thanks.


Solution

  • Have you tried saving as a temporary file in windows?

    tmp <-  tempfile()
    download.file(
    'http://mirtarbase.mbc.nctu.edu.tw/cache/download/7.0/miRTarBase_MTI.xlsx', tmp, mode = "wb")
    readxl::read_excel(tmp) -> miRTarBase
    write.csv(miRTarBase, 'miRTarBase.csv')
    read.csv('miRTarBase.csv', row.names = 1) -> miRTarBase
    file.remove(tmp)