Automatically Delete Files/Folders

前端 未结 5 563
自闭症患者
自闭症患者 2020-11-27 04:09

Is there any way to automatically delete all files or folders with few R command lines? I am aware of the unlink() or file.remove() functions, but

相关标签:
5条回答
  • 2020-11-27 04:43

    For all files in a known path you can:

    unlink("path/*")
    
    0 讨论(0)
  • 2020-11-27 04:59

    Using a combination of dir and grep this isn't too bad. This could probably be turned into a function that also tells you which files are to be deleted and gives you a chance to abort if it's not what you expected.

    # 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 讨论(0)
  • 2020-11-27 05:04

    Maybe you're just looking for a combination of file.remove and list.files? Maybe something like:

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

    And I guess you can filter the list of files down to those whose names match a certain pattern using grep or grepl, no?

    0 讨论(0)
  • 2020-11-27 05:05
    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
    ))
    

    You can also use unlink as an alternative to file.remove.

    0 讨论(0)
  • 2020-11-27 05:08

    I quite like here::here for finding my way through folders (especially if I'm switching between inline evaluation and knit versions of an Rmarkdown notebook)... yet another solution:

        # 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))
    
    0 讨论(0)
提交回复
热议问题