自动删除文件/文件夹

问题描述 投票:0回答:6

有没有什么方法可以用很少的R命令行自动删除所有文件或文件夹? 我知道

unlink()
file.remove()
函数,但对于这些函数,您需要定义一个字符向量,其中包含要删除的文件的所有名称。我正在寻找更多列出特定路径(例如“C:/Temp”)内的所有文件或文件夹的内容,然后删除具有特定名称的所有文件(无论其扩展名是什么)。

非常感谢任何帮助!

r file path directory delete-file
6个回答
84
投票

也许您只是在寻找

file.remove
list.files
的组合?也许是这样的:

do.call(file.remove, list(list.files("C:/Temp", full.names = TRUE)))

我想您可以使用

grep
grepl
将文件列表过滤到名称与特定模式匹配的文件,不是吗?


84
投票

对于已知路径中的所有文件,您可以:

unlink("path/*")

29
投票
dir_to_clean <- tempdir() #or wherever

#create some junk to test it with
file.create(file.path(
  dir_to_clean, 
  paste("test", 1:5, "txt", sep = ".")
))

#Now remove them (no need for messing about with do.call)
file.remove(dir(  
  dir_to_clean, 
  pattern = "^test\\.[0-9]\\.txt$", 
  full.names = TRUE
))

您还可以使用

unlink
作为
file.remove
的替代品。


6
投票

删除文件夹内的所有内容,但保持文件夹为空

unlink("path/*", recursive = TRUE, force = TRUE)

删除文件夹内的所有内容,同时删除文件夹

unlink("path", recursive = TRUE, force = TRUE)

使用

force = TRUE
覆盖任何只读/隐藏/等。问题。


4
投票

结合使用 dir 和 grep 这还不错。这可能会变成一个函数,它还可以告诉您要删除哪些文件,并在不符合您的预期时给您一个中止的机会。

# Which directory?
mydir <- "C:/Test"
# What phrase do you want contained in
# the files to be deleted?
deletephrase <- "deleteme"

# Look at directory
dir(mydir)
# Figure out which files should be deleted
id <- grep(deletephrase, dir(mydir))
# Get the full path of the files to be deleted
todelete <- dir(mydir, full.names = TRUE)[id]
# BALEETED
unlink(todelete)

0
投票

我非常喜欢

here::here
来查找文件夹中的路径(特别是当我在 Rmarkdown 笔记本的内联评估和 knit 版本之间切换时)...还有另一个解决方案:

    # Batch remove files
    # Match files in chosen directory with specified regex
    files <- dir(here::here("your_folder"), "your_pattern") 

    # Remove matched files
    unlink(paste0(here::here("your_folder"), files))
© www.soinside.com 2019 - 2024. All rights reserved.