导入文本文件时跳过空文件 [英] Skip empty files when importing text files

查看:125
本文介绍了导入文本文件时跳过空文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要导入约700个文本文件的文件夹,并向其中添加一列.我已经弄清楚了如何使用以下代码做到这一点:

I have a folder with about 700 text files that I want to import and add a column to. I've 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")

问题是,大约有100个文件为空.所以代码在第一个空文件处停止,我收到此错误消息:

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

Error in read.table(f, header = F, sep = ",") : 
  no lines available in input

是否可以跳过这些空文件?

Is there a way to skip over these empty files?

推荐答案

对于引入显式错误处理的另一种方法,请考虑使用tryCatch处理在您的read.table中可能发生的其他不良情况.

For a different approach that introduces explicit error handling, think about a tryCatch to handle anything else bad that might happen in your 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)
}

这篇关于导入文本文件时跳过空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆