Reputation: 77
Is there a way to read an Excel file into R directly from a folder without having to specify the filename? I'm using the readxl library and I have only 1 file in the folder, but the file's name changes monthly.
Thanks!
Upvotes: 1
Views: 1989
Reputation: 545923
As noted in other answers, this can be solved using the dir
function.
Assuming the variable path
contains the path of the directory in which the XLSX file is located, then the following will give you the full path to the file:
file_path = dir(path, pattern = '\\.xlsx$', full.names = TRUE)
Note that pattern
uses regular expressions rather than glob format! Using the glob pattern *.xlsx
might appear to work but it’s incorrect, only works by accident, and will also match other file names.
Upvotes: 1
Reputation: 213
Suppose your file is located inside a folder called myFolder
located in disk E:\\
library(readxl)
folderPath <- "E://myFolder"
fileName <- grep(".xlsx", dir(folderPath), value = TRUE)
filePath <- paste(folderPath, fileName, sep = "//")
df <- read_xlsx(filePath)
This code will get the name of your xlsx file inside folderPath
each time you run it and then you can import it with readxl::read_xlsx
. I assume there is only one xlsx file inside the folder.
Upvotes: 0
Reputation: 1095
The computer need to have the path anyway BUT you can get it without giving if you are absolutly sure that this is the only one file in your folder
see https://stat.ethz.ch/R-manual/R-devel/library/base/html/list.files.html to learn more about how to open a directory and getting filename inside.
If this isn't the only file but this is the only excel file you while have to get the extension of each file and do some parsing to take a decision of wich file you want to open
Upvotes: 2