How to skip empty files when importing text files into R?

I have a folder with 700 text files that I want to import and add a column. I figured out how to do this using the following code:

files = list.files(pattern = "*c.txt")
DF <- NULL
for (f in files) {
  data <- read.table(f, header = F, sep=",")
  data$species <- strsplit(f, split = "c.txt") <-- (column name is filename)
  DF <- rbind(DF, data)
}
write.xlsx(DF,"B:/trends.xlsx")

The problem is that there are about 100 files that are empty. so the code stops in the first empty file, and I get this error message:

Error in read.table (f, header = F, sep = ","): there are no lines in the input line

Is there any way to skip these empty files?

Thanks!

+4
source share
2 answers

, , tryCatch, - , read.table.

for (f in files) {
    data <- tryCatch({
        if (file.size(f) > 0){
        read.table(f, header = F, sep=",")
           }
        }, error = function(err) {
            # error handler picks up where error was generated
            print(paste("Read.table didn't work!:  ",err))
        })
    data$species <- strsplit(f, split = "c.txt") 
    DF <- rbind(DF, data)
}
+1

, , file.size(some_file) > 0:

files <- list.files("~/tmp/tmpdir", pattern = "*.csv")
##
df_list <- lapply(files, function(x) {
    if (!file.size(x) == 0) {
        read.csv(x)
    }
})
##
R> dim(do.call("rbind", df_list))
#[1] 50  2

10 , , 10, .


:

for (i in 1:10) {
    df <- data.frame(x = 1:5, y = 6:10)
    write.csv(df, sprintf("~/tmp/tmpdir/file%i.csv", i), row.names = FALSE)
    ## empty file
    system(sprintf("touch ~/tmp/tmpdir/emptyfile%i.csv", i))
}
+3

Source: https://habr.com/ru/post/1611976/


All Articles