0

I have the following script:

Files <- list.files(datapath, pattern = ".txt")


# convert all .txt files in the given folder
for (i in 1:length(Files)){
  dataname <- Files[i]
  filename <- paste(datapath, dataname, sep="")

  read_eprime(filename) %>% FrameList() %>% to_data_frame() %>% select(Cue:ISIslide.RT, GetReady.OnsetTime, ScanWait.OffsetTime) %>% slice (-1) %>%  
    fill(GetReady.OnsetTime, .direction = "up") %>% fill(ScanWait.OffsetTime, .direction = "up") %>% slice (-79) -> edf


  write.csv(edf, file = paste0(datapath, dataname, "_P.csv"), na = "", row.names = FALSE)

  #write.csv(edf, file=paste0(datapath, "tsv_", dataname), quote=FALSE, sep="\t", na = "")
}

How do I adjust it, so that the output files do not save with ".txt" in the middle of the name?

KKhosra
  • 163
  • 1
  • 4
  • 9
  • Possible duplicate of [Splitting a file name into name,extension](https://stackoverflow.com/questions/14173754/splitting-a-file-name-into-name-extension) – GordonShumway Jul 06 '18 at 20:28

2 Answers2

2

Check out file_path_sans_ext for getting the filename. This is from the built-in tools package and will return only the filename without the extension.

tools::file_path_sans_ext("myFile.txt")
## [1] "myFile"

You can also use this instead of pasting the file path to the file name.

tools::file_path_sans_ext("Downloads/Stuff/myFile.txt")
## [1] "Downloads/Stuff/myFile"
gos
  • 474
  • 4
  • 18
0

You can think of using gsub to replace .txt with "" from dataname as:

gsub("\\.txt","","file.txt")
#[1] "file"

dataname <- "myFile.txt"

gsub("\\.txt","",dataname)
#[1] "myFile"

dataname <- "Downloads/Stuff/myFile.txt"
gsub("\\.txt","",dataname)
#[1] "Downloads/Stuff/myFile"

The good part with gsub is that it can correct multiple occurrence of ".txt" as well. e.g.:

dataname <- "Downloads/Stuff/my.txtFile.txt"
gsub("\\.txt","",dataname)
#[1] "Downloads/Stuff/myFile"
MKR
  • 19,739
  • 4
  • 23
  • 33