2

I am trying to loop through all csv filenames in a certain folder directory on my computer. Once this is done I want to be perform a string split on the filenames. Is there a way an efficient way of doing this?

At the moment I am entering the string of the filename manually in my code and them performing the string split on that string but this is not efficient...

file <- "test_1.csv"
Lynda
  • 141
  • 7
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Oct 10 '19 at 20:42
  • What string split are you trying to do? – camille Oct 10 '19 at 20:42

3 Answers3

4

Assuming that the working directory is set on the folder where we want to extract the file names, use list.files

files <- list.files(pattern = "\\.csv$", full.names = FALSE, ignore.case = TRUE)

and use regex to extract

sub("\\.csv", "", files)

Or use a convenient function from the tools package

tools::file_path_sans_ext(files)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thanks @akrun! I have set the working directory and this works really well! I used the regex to extract but just out of curiosity can you explain the function from the tools package? – Lynda Oct 10 '19 at 20:41
  • 1
    @Lynda It is a package available when you install `base R`. It extracts the string before the extension ie. `.csv` part would be removed – akrun Oct 10 '19 at 20:42
  • 1
    Ok thanks for clarifying @akrun! So it pretty much does the same thing as the regex. – Lynda Oct 10 '19 at 20:44
  • 1
    +1 I use this all the time. You may want to add `ignore.case = TRUE` in case there are any ".CSV" files in there. There are other useful switches for directory searching etc. – Dan Slone Oct 10 '19 at 20:55
0

You can run something like this Directory.GetFiles(DirectoryOfAllTheCSVFiles, "*.csv")

This will create a collection of all the CSV files with the file path. Then run through collection and do something like this

Path.GetFileNameWithoutExtension(file.Name)

It will return the file name without the extension.

Andy
  • 11
  • 1
  • 3
0

Read all the files in a given folder. First, save the route.

files <- list.files(path = "//server/route/folder", pattern = "*.csv", full.names = T)

Then, read all at the same time and turn it into a dataframe.

data <-  sapply(files, read_csv, simplify=FALSE)%>%bind_rows(.id = "column_name_here_for_each_file")

Ivancito
  • 159
  • 1
  • 11