Leprechault
Leprechault

Reputation: 1823

readr::read_lines: Problem with lines length result for empty *txt files

I have 4K *txt files where the numbers of lines are important because if my *txt file is empty a need to count zero and if I have 1 or more lines this information is informative too. But the function read_lines in readr package give to me 1 line always that I have an empty file, in my example:

library(tidyverse)

# *txt file with 1 line
myfile1<-read_lines("https://raw.githubusercontent.com/Leprechault/trash/main/sample_672.txt")
length(myfile1)
#[1] 1
myfile1
#[1] "0 0.229592 0.382716 0.214286 0.246914"

# *txt file with 0 line
myfile2<-read_lines("https://raw.githubusercontent.com/Leprechault/trash/main/sample_1206.txt")
length(myfile2)
#[1] 1
myfile2
#[1] ""

In myfile1 is OK, because I have 1 line, but in the second case (myfile2) I don't have one line and the file is empty. Please, how can I solve this problem?

Upvotes: 2

Views: 189

Answers (2)

guRu
guRu

Reputation: 31

You can use readLines() from base R. It already has the correct behavior.

Upvotes: 3

Ben Bolker
Ben Bolker

Reputation: 226871

You can put read_lines() inside a wrapper function that does what you want ...

rl <- function(...) {
    x <- read_lines(...)
    if (identical(x,"")) return(character(0))
    return(x)
}

rl("https://raw.githubusercontent.com/Leprechault/trash/main/sample_1206.txt")  
## character(0)

Upvotes: 1

Related Questions