有没有办法用少量R命令自动删除所有文件或文件夹?
我知道unlink()
或file.remove()
函数,但是对于这些函数,您需要定义一个字符向量,并且确切地列出要删除的所有文件的名称。我更希望能够列出特定路径(例如'C:/Temp')中的所有文件或文件夹,然后删除所有具有特定名称的文件(无论其扩展名如何)。
非常感谢任何帮助!
有没有办法用少量R命令自动删除所有文件或文件夹?
我知道unlink()
或file.remove()
函数,但是对于这些函数,您需要定义一个字符向量,并且确切地列出要删除的所有文件的名称。我更希望能够列出特定路径(例如'C:/Temp')中的所有文件或文件夹,然后删除所有具有特定名称的文件(无论其扩展名如何)。
非常感谢任何帮助!
对于已知路径下的所有文件,您可以:
unlink("path/*")
也许您只是在寻找 file.remove
和 list.files
的组合?或许可以尝试如下代码:
do.call(file.remove, list(list.files("C:/Temp", full.names = TRUE)))
我猜你可以使用grep
或grepl
过滤文件列表,只保留那些文件名符合特定模式的文件,对吗?
list.files
的pattern
参数(或其同义词dir
),默认情况下它们会产生一个向量,因此需要将list
函数用于do.call
的操作。请注意,翻译保持原意,不包含任何解释性内容。 - Jamesdo.call
;请看我的回答。 - Richie Cottondir_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
的替代方案。
删除文件夹中的所有内容,但保留空文件夹。
unlink("path/*", recursive = T, force = T)
unlink("path", recursive = T, force = T)
使用force = T
,覆盖任何只读/隐藏等问题。
# 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)
dir
命令接受一个 pattern
参数,因此您无需单独使用 grep
命令。 - Richie Cotton我非常喜欢使用here::here
来浏览文件夹(特别是当我在Rmarkdown笔记本的内联评估和编织版本之间切换时)...这是另一种解决方案:
# 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))
recursive=TRUE
和force=TRUE
会有所帮助。 我在Linux上。 - Ufos