How can I check if a file is empty?

后端 未结 4 2064
春和景丽
春和景丽 2021-02-18 18:51

I have thousands of text files and would like to know how to check if a particular file is empty. I am reading all the files using this line of code

Y<-grep(\         


        
相关标签:
4条回答
  • 2021-02-18 19:23

    Use the following code to check if a file in the system is empty or not before uploading it.

    my_file<-readLines(paste0("<path of file/file name.extension>"))
    my_file=="" #TRUE - means the file is empty
    
    0 讨论(0)
  • 2021-02-18 19:42

    For a functional approach, you might first write a predicate:

    file.empty <- function(filenames) file.info(filenames)$size == 0
    

    And then filter the list of files using it:

    Filter(file.empty, dir())
    
    0 讨论(0)
  • 2021-02-18 19:46

    You can use file.info for that:

    info = file.info(filenames)
    empty = rownames(info[info$size == 0, ])
    

    Incidentally, there’s a better way of listing text files than using grep: specify the pattern argument to list.files:

    list.files(pattern = '\\.txt$')
    

    Notice that the pattern needs to be a regular expression, not a glob – the same is true for grep!

    0 讨论(0)
  • 2021-02-18 19:46
    find . -empty 
    

    or

    find . -empty |awk -F\/ '{print $FN}'
    

    If you want to limit just txt files:

    find . -empty -name "*.txt"
    

    If you want only asci files (not just .txt)

    find . -empty -type f
    

    put it all together:

    find . -empty -type f -name "*.txt" |awk -F\/ '{print $NF}'
    
    0 讨论(0)
提交回复
热议问题