0

I have a folder with about 100 file txt. I only run simpl code:

> setwd("E:/Yunlin/SMUNPO/TXTFILE/")
> filenames <- list.files(getwd(),pattern="*.txt")
> textfiles <- lapply(filenames, readLines)

However, the result is Error in file(con, "r") : cannot open the connection. I tried to set the working directory, change the file name to be simple, but none of it works. I test with readLines function for a specific file name. It works. But not for all the folder. Anyone can help, thank you in advanced?

r2evans
  • 77,184
  • 4
  • 55
  • 96

1 Answers1

0
  • You must use regex-style patterns in pattern, not glob-style.

    From ?list.files:

     pattern: an optional regular expression.  Only file names which match
              the regular expression will be returned.
    

    So it is expecting regex, not glob-style patterns.

    Use one of these options:

    list.files(pattern = "\\.txt$")
    list.files(pattern = utils::glob2rx("*.txt"))
    

    (To learn regex, I suggest both https://stackoverflow.com/a/22944075/3358272 and https://www.regular-expressions.info/. Note that backslashes in regular expressions usually need to be double-blackslashes; for example, \b (word boundary) in R needs to be \\b.)

  • You should use full.names=TRUE, precluding the need for the setwd/getwd dance. I suggest something like:

    # no need for `setwd`
    filenames <- list.files("E:/Yunlin/SMUNPO/TXTFILE/", pattern = "\\.txt$", full.names = TRUE)
    
r2evans
  • 77,184
  • 4
  • 55
  • 96