0

I need to iterate through some files (a lot actually) and fix some issues via gsub.

library(xml2)
library(magrittr)
lapply(list.files(folder, full.names = TRUE), function(file){
    tryCatch(a1 <- xml2::read_xml(file),
             error = function(e){
               fix_to_write <- readLines(file) %>%
                 gsub("&", "and", .)
               writeLines(fix_to_write, file)
             })
  })

The problem is after a while i get the error that it cant open my a file: :

In readLines(file_to_open) : kann Datei '/Volumes/data/welt/xml_out/2012-02/13858485.xml' nicht öffnen: Too many open files Ausführung angehalten rm: /var/folders/39/z521yg593sx8_thrj843qj_r0000gn/T//Rtmpw4AKJr: Too many open files

I tried to various solutions like "closeAllConnections()" or "close(file)". Nothing worked. Any suggestions? I work on Mac...

Regards

1 Answer 1

0

Just a guess as I've never run into that problem myself, but I assume this should work:

lapply(list.files(folder, full.names = TRUE), function(file){
  tryCatch(a1 <- xml2::read_xml(file),
           error = function(e){
             con <- file(description = file)
             fix_to_write <- readLines(file) %>%
               gsub("&", "and", .)
             close(con)
             writeLines(fix_to_write, file)
           })
})

readLines will actually open a connection to the file if provided a character string. This should be closed on exit but maybe it makes more sense to do it explicitly. Let me know if this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.