【问题标题】:How do I remove a portion of the name when saving a file?保存文件时如何删除部分名称?
【发布时间】:2018-12-15 11:02:46
【问题描述】:

我有以下脚本:

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 = "")
}

如何调整,使输出文件不保存名称中间有“.txt”?

【问题讨论】:

标签: r export filenames readxl


【解决方案1】:

查看file_path_sans_ext 以获取文件名。这来自内置 tools 包,将仅返回不带扩展名的文件名。

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

您也可以使用它来代替将文件路径粘贴到文件名。

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

【讨论】:

    【解决方案2】:

    您可以考虑使用gsub.txt 替换为来自dataname 的""

    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"
    

    gsub 的好处在于它还可以更正多次出现的“.txt”。例如:

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

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多