Reputation: 345
Sometimes I have to use R code to remove files in specific folders. To make sure i never remove something by accident I want to use pattern
to make sure only desired files will be remove (so if I use wrong dir nothing will happen):
file.remove(dir(path="D:/Folder/RestOfMyPath/",pattern="*_pattern.csv"))
And i get:
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[18] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
There were 28 warnings (use warnings() to see them)
And were i type warnings()
:
1: In file.remove(dir(path = "D:/Folder/RestOfMyPath/", ... :
cannot remove file 'my_file1_pattern.csv', reason 'No such file or directory'
I can see the files (my_file1_pattern.csv for example) are there. I can open them or delete manually. They all are generated by R but they are regular .csv files. The weirdest part is that this sometimes works but only as it feels like it. Sometimes i get TRUE
instead FALSE
and files are removed (rarely). But I cant figure out how to control it. I use R studio but same problem occurs in raw R.
Upvotes: 1
Views: 2563
Reputation: 4960
file.remove
is looking in the working directory for the files that you dir
'ed in the other directory you supplied. dir
's output is just the file names.
Try
mydir <- "D:/Folder/RestOfMyPath/"
delfiles <- dir(path=mydir ,pattern="*_pattern.csv"))
file.remove(file.path(mydir, delfiles))
The "TRUE" instances are you blowing out (the wrong) files in the working directory that share the same name.
Upvotes: 5